下面的代碼也能實現相同的功能,為何要引入 fn.init 這個東西呢? 好處是什么?
var $$$ = ajQuery2 = function(selector) {
? ? if(!(this instanceof(ajQuery2))){
? ? ? ? ?return new ajQuery2(selector);?
? ? }
? ? this.selector = selector;
}
ajQuery2.prototype = {
? ? name: 'aaron',
? ? init: function(selector) {
? ? ? ? this.selector = selector;
? ? ? ? return this;
? ? },
? ? constructor: ajQuery2
}
var a = ajQuery2("abc");
console.dir(a);
2016-01-24
按照你的代碼 ajQuery2('#abc') ?這樣, 每次調用ajQuery 都會判斷 this instanceof(ajQuery2) 2次, 第一次this 肯定是指向window,然后第二次才指向 new ajQuery2生成的實例,按照jQuery的設計就分開來了,那樣的話就不需要判斷是否是jQuery構造器的實例了,(jQuery通過一些巧妙的寫法使返回的對象就像是通過 ? ? ? ? ? ? ? ? ?new jQuery(selector)生成的一樣,具體代碼是
)其實到這邊也不是什么大問題,至少你發的那些解決了死循環的問題。 ??
其次就是要涉及到后面jQuery里面工具方法(也叫靜態方法)和實例方法的設計了,這邊的$.fn只是$.prototype的一個別名而已,如果按照你代碼那樣,其實也是可以實現ajQuery 和ajQuery.prototype 兩者分別的拓展extend,然后在ajQuery.prototype上擴展的方法調用ajQuery上的方法,所以引入fn.init主要應該還是因為內部構造器jQuery.fn.init和jQuery本身分開比較優雅
2015-12-16
就看見好看就好看