首页 > javascript中原型对象的指向问题。。

javascript中原型对象的指向问题。。

jQuery.fn = jQuery.prototype = {
    // The current version of jQuery being used
    jquery: core_version,
    constructor: jQuery    // ??这里的疑惑
}

上面是jQuery的部分源码,我想知道为什么给jQuery的原型对象上的constructor重新指向jQuery?不重新指向的话会出现什么问题?


因为使用jQuery.prototype = {}这样就会是constructor指向Object了,使用要重新更改constructor,改为jQuery.

{}对象字面量,它的constructor是Object
所以jquery.prototype={},就会使jquery.prototype的constroctor变为Object。
至于不重新指向有什么结果,只要你在后面的代码中不用到constroctor这个属性的时候,其实是没什么影响的。
比如你要检查构造函数是哪个,那么就有影响。


jQuery.prototype={}之后,jQuery.prototype会被新赋给他的对象覆盖掉,故原来jQuery.prototype中的constructor就失效了


因为默认情况下任何对象(这里是 jQuery )的原型对象有一个 contructor 的属性,指向这个对象本身,而 jQuery.prototype = {} 相当于重写的 jQuery 的原型对象,所以在这个地方需要重新写上 constructor: jQuery


简单来说 不指向的话typeof得到的是Object类型。指向jQuery构造函数。用typeof得到是jQuery对象。


jQuery.prototype = {}
这里jQuery.prototype被修改指向了 {}对象,因此需要重新修正,让他指向jQuery
关于原型基础的详细讲解,推荐阅读《Javascript高级编程》,精品。


这里把jQuery.prototype重新赋值了,所以原来的jQuery.prototype.constructor会被覆盖掉。如果jQuery失去constructor的话,就不能通过constructor来构造一个同类型的新对象,也不能用来判断自己的类型。例如下面的代码:

Test = function () {
    this.name = "hello";
}

Test.prototype = {};
var t1 = new Test;
var t2 = new t1.constructor;
console.log(t1.constructor === Object); // true
console.log(t2.name); // undefined

参考:http://javascript.info/tutorial/constructor

【热门文章】
【热门文章】