发布时间:2025-12-10 23:19:49 浏览次数:1
constructor属性始终指向创建当前对象的构造函数。比如下面例子:
//等价于varfoo=newArray(1,56,34,12);vararr=[1,56,34,12];console.log(arr.constructor===Array);//true//等价于varfoo=newFunction();varFoo=function(){};console.log(Foo.constructor===Function);//true//由构造函数实例化一个obj对象varobj=newFoo();console.log(obj.constructor===Foo);//true//将上面两段代码合起来,就得到下面的结论console.log(obj.constructor.constructor===Function);//true但是当constructor遇到prototype时,有趣的事情就发生了。
我们知道每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数。如下例所示:
functionPerson(name){this.name=name;};Person.prototype.getName=function(){returnthis.name;};varp=newPerson("ZhangSan");console.log(p.constructor===Person);//trueconsole.log(Person.prototype.constructor===Person);//true//将上两行代码合并就得到如下结果console.log(p.constructor.prototype.constructor===Person);//true当时当我们重新定义函数的prototype时(注意:和上例的区别,这里不是修改而是覆盖),constructor属性的行为就有点奇怪了,如下示例:
functionPerson(name){this.name=name;};Person.prototype={getName:function(){returnthis.name;}};varp=newPerson("ZhangSan");console.log(p.constructor===Person);//falseconsole.log(Person.prototype.constructor===Person);//falseconsole.log(p.constructor.prototype.constructor===Person);//false为什么呢?
原来是因为覆盖Person.prototype时,等价于进行如下代码操作:
Person.prototype=newObject({getName:function(){returnthis.name;}});而constructor属性始终指向创建自身的构造函数,所以此时Person.prototype.constructor === Object,即是:
functionPerson(name){this.name=name;};Person.prototype={getName:function(){returnthis.name;}};varp=newPerson("ZhangSan");console.log(p.constructor===Object);//trueconsole.log(Person.prototype.constructor===Object);//trueconsole.log(p.constructor.prototype.constructor===Object);//true怎么修正这种问题呢?方法也很简单,重新覆盖Person.prototype.constructor即可:
functionPerson(name){this.name=name;};Person.prototype=newObject({getName:function(){returnthis.name;}});Person.prototype.constructor=Person;varp=newPerson("ZhangSan");console.log(p.constructor===Person);//trueconsole.log(Person.prototype.constructor===Person);//trueconsole.log(p.constructor.prototype.constructor===Person);//true“JavaScript中的constructor属性怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!