主要区别在于:第一段代码中有个关键字“new”,所以呢最后的“$()”是一个实例化对象,这个实例化对象的构造函数是“jQuery.fn.init”,它的原型对象是“jQuery.fn”。此外,这个实例化对象自身有一个length属性(由this.length=1指定),而它的原型对象有length(length:0)、jquery两个属性和init、size两个方法,所以$()实际上是有两个length属性,但是当读取对象属性的时候,会先从对象自身查找有没有这个属性,有的话就立即读取并停止查找,没有的话才会继续向上 在它的原型里找,显然$()对象自身有length属性且值为1,所以最终弹出1。第二段代中,“$()”只是单纯的执行了一下jQuery.fn.init这个函数,作用是将jQuery.fn的length属性赋值为1并返回jQuery.fn对象。所以,$()=jQuery.fn,它的length自然也是1。
两段代码中“$()”所指向的对象不同,跟作用域关系不大~
两段代码中“$()”所指向的对象不同,跟作用域关系不大~
var $ = jQuery = function() {
return new jQuery.fn.init();
}
new jQuery.fn.init(); new + jQuery.fn.init;里面的this 是 jQuery.fn.init.prototype var $ = jQuery = function() {
return jQuery.fn.init();
}
jQuery.fn.init(); init 里面的this 是jQuery.fn;因为jQuery.fn.init.prototype = jQuery.prototype; 所以,你说是不是一样。
[email protected]
还得再问你一个问题,就是我刚刚看李战的那个甘露模型我对立面的一个点有点儿疑问,我把代码贴出来你帮我看看function New(aClass, aParams) {
function new_() {
aClass.create.apply(this, aParams); //原文写法
//aClass.create.apply(aClass, aParams); //我自己的写法
}
new_.prototype = aClass;
return new new_();
}
var Person = {
create : function(name, age) {
this.name = name;
this.age = age;
},
say : function() {
alert("Hello, I'm " + this.name);
}
};
var koma = New(Person, ['koma', 21]);
koma.say();
alert( koma.constructor );
对于我标记出来的那个地方,他原来用的是this,那我有个疑问就是aClass.create.apply(this, aParams); 这里的this是指向哪里的?跟直接用aClass有什么区别吗?然后就是有什么方法能够打印出this是指向谁的吗?
生成:
koma = new_;
new_是一个函数.一个设定自己prototype的函数。
他之所以不一开始,不直接koma = new_ 是他那地方用到闭包,也就是通过闭包,把aClass, aParams,参数赋给他们。
说白了就是
koma = new_; 同时aClass, aParams变量值,已经设好了。
function New(aClass, aParams) {
function new_() {
aClass.create.apply(this, aParams); //原文写法
//aClass.create.apply(aClass, aParams); //我自己的写法
}
new_.prototype = aClass;
return new_;
}
var Person = {
create : function(name, age) {
this.name = name;
this.age = age;
},
say : function() {
alert("Hello, I'm " + this.name);
}
};
var komaClass = New(Person, ['koma', 21]);
var kObj = new komaClass();
kObj.say();
alert( kObj.constructor );