【前端面試】字節跳動2019校招面經 - 前端開發崗(二)
因為之前的一篇篇幅有限,太長了看著也不舒服,所以還是另起一篇吧?
一、 jQuery和Vue的區別
jQuery 輕量級Javascript庫
Vue 漸進式Javascript-MVVM框架
jQuery和Vue的對比
- jQuery使用了選擇器(
$函數
)選取DOM對象,對其進行賦值、取值、事件綁定等操作,和原生的HTML的區別只在于可以更方便的選取和操作DOM對象,而數據和界面是在一起的。比如需要獲取label標簽的內容:$("lable").val();,它還是依賴DOM元素的值。 - Vue通過Vue對象和數據的雙向綁定機制,將數據和View完全分離開來。在Vue中,對數據進行操作不再需要引用相應的DOM對象,可以說數據和View是分離的。
-
再說一些Vue相比jQuery而言所具有的優勢
- 組件化開發,提高代碼的復用
- 數據和視圖分離,便于維護和操作
- 虛擬DOM,在無需關心DOM操作的基礎上,依然提供了可靠的性能
二、 模擬jQuery的選擇器($())實現
源碼如下
(function(){jQuery = function( selector, context ) {// The jQuery object is actually just the init constructor 'enhanced'return new jQuery.fn.init( selector, context, rootjQuery );};if ( typeof window === "object" && typeof window.document === "object" ) {window.jQuery = window.$ = jQuery;}
})();
最簡單的方法
僅僅對于IE8及以上有效
(function(){var jQuery = function(selector){return document.querySelectorAll(selector);};window.jQuery = window.$ = jQuery;
})();
querySelectorAll()返回的是DOM原生element對象
而jQuery的選擇器返回的是jQuery的包裝對象,同時包含了原生DOM對象和一些jQuery的構造函數所具有的屬性
稍微復雜一點的實現方法
(function(){var jQuery = function(selector){var result = {};if (selector.substring(0,1) === "#") {result = document.getElementById(selector.substring(1));// this.tqOjbect.data.push(elem);} else if (selector.substring(0,1) === ".") {result = document.getElementsByClassName(selector.substring(1));} else {result = document.getElementsByTagName(selector);}return result;};window.jQuery = window.$ = jQuery;
})();
三、jQuery的鏈式調用實現
var MyJQ = function(){}
MyJQ.prototype = {css:function(){console.log("設置css樣式");return this;},show:function(){console.log("將元素顯示");return this;},hide:function(){console.log("將元素隱藏");}};
var myjq = new MyJQ();
myjq.css().css().show().hide();