jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery // ??这里的疑惑
}
上面是jQuery的部分源码,我想知道为什么给jQuery的原型对象上的constructor重新指向jQuery?不重新指向的话会出现什么问题?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为使用jQuery.prototype = {}这样就会是constructor指向Object了,使用要重新更改constructor,改为jQuery.
{}是对象字面量,它的constructor是Object。所以jquery.prototype={},就会使jquery.prototype的constroctor变为Object。
至于不重新指向有什么结果,只要你在后面的代码中不用到constroctor这个属性的时候,其实是没什么影响的。
比如你要检查构造函数是哪个,那么就有影响。
jQuery.prototype={}之后,jQuery.prototype会被新赋给他的对象覆盖掉,故原来jQuery.prototype中的constructor就失效了
jQuery.prototype = {}这里jQuery.prototype被修改指向了
{}对象,因此需要重新修正,让他指向jQuery关于原型基础的详细讲解,推荐阅读
《Javascript高级编程》,精品。因为默认情况下任何对象(这里是
jQuery)的原型对象有一个contructor的属性,指向这个对象本身,而jQuery.prototype = {}相当于重写的jQuery的原型对象,所以在这个地方需要重新写上constructor: jQuery。简单来说 不指向的话typeof得到的是Object类型。指向jQuery构造函数。用typeof得到是jQuery对象。