var aQuery = function(selector, context) {
return aQuery.prototype.init();
}
aQuery.prototype = {
init: function() {
this.age = 18
return this;
},
name: function() {},
age: 20
}
aQuery().age //18
这样的情况下就出错了,因为this只是指向aQuery类的,所以需要设计出独立的作用域才行
jQuery框架分隔作用域的处理
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor ‘enhanced’
return new jQuery.fn.init( selector, context, rootjQuery );
},
很明显通过实例init函数,每次都构建新的init实例对象,来分隔this,避免交互混淆
那么既然都不是同一个对象那么肯定又出现一个新的问题
例如:
var aQuery = function(selector, context) {
return new aQuery.prototype.init();
}
aQuery.prototype = {
init: function() {
this.age = 18
return this;
},
name: function() {},
age: 20
}
//Uncaught TypeError: Object [object Object] has no method ‘name’
console.log(aQuery().name())
抛出错误,无法找到这个方法,所以很明显new的init跟jquery类的this分离了
怎么访问jQuery类原型上的属性与方法?
做到既能隔离作用域还能使用jQuery原型对象的作用域呢,还能在返回实例中访问jQuery的原型对象?
实现的关键点
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
通过原型传递解决问题,把jQuery的原型传递给jQuery.prototype.init.prototype
换句话说jQuery的原型对象覆盖了init构造器的原型对象
因为是引用传递所以不需要担心这个循环引用的性能问题
var aQuery = function(selector, context) {
return new aQuery.prototype.init();
}
aQuery.prototype = {
init: function() {
return this;
},
name: function() {
return this.age
},
age: 20
}
aQuery.prototype.init.prototype = aQuery.prototype;










