JavaScript重写constructor属性的问题

60 篇文章 0 订阅
55 篇文章 1 订阅
console.log("-----------------------使用原型实现继承---------------------------");
function Person() {

}
Person.prototype.dance = function () {};

function NinjaTestInherit() {}
//通过将NinjaTest的原型赋值给Person实例,实现NinjaTestInherit继承Person.
NinjaTestInherit.prototype = new Person();

const ninjaTestInherit = new NinjaTestInherit();
if (ninjaTestInherit instanceof NinjaTestInherit) {
  console.log("ninjaTestInherit receives functionally from the NinjaTestInherit proptype");
}
if (ninjaTestInherit instanceof Person) {
  console.log("... and the Person proptype");
}
if (ninjaTestInherit instanceof Object) {
  console.log("... and the Object proptype");
}
if (typeof ninjaTestInherit.dance === "function") {
  console.log("... and can dance!");
}

Person.prototype.sing = function () {}
if (typeof ninjaTestInherit.sing !== "function") {
  console.log("ninjaTestInherit can not sing!");
} else {
  console.log("ninjaTestInherit can sing!-->" + ninjaTestInherit.sing);
}

Person.prototype.dance = null;
if (ninjaTestInherit.dance != null) {
  console.log("ninjaTestInherit is not null-->!" + ninjaTestInherit.dance);
} else {
  console.log("ninjaTestInherit is null!-->" + ninjaTestInherit.dance);
}

if (ninjaTestInherit.constructor === NinjaTestInherit) {
  console.log("The ninjaTestInherit object was created by the NinjaTestInherit constructor");
} else {
  console.log("The ninjaTestInherit object was not created by the NinjaTestInherit constructor");
}

if (ninjaTestInherit.constructor === Person) {
  console.log("The ninjaTestInherit object was created by the Person constructor");
} else {
  console.log("The ninjaTestInherit object was not created by the Person constructor");
}

 

 

从上图发现,通过设置Person实例对象作为NinjaTestInherit构造器的原型时,我们丢失了NinjaTestInherit与NinjaTestInherit初始原型之间的关联。这是一个问题,因为constructor属性可用于检测一个对象是否由某一个函数创建的。

if (ninjaTestInherit.constructor === NinjaTestInherit) {

console.log("The ninjaTestInherit object was created by the NinjaTestInherit constructor");

} else {

console.log("The ninjaTestInherit object was not created by the NinjaTestInherit constructor");

}

通过上述方式测试:发现无法查找到NinjaTestInherit 对象的constructor属性。回到原型上,原型上也没有constructor属性,继续在原型链上追溯,在Person对象的原型上具有指向Person本身的constructor属性。事实上我们查找ninjaTestInherit 对象的构造函数,我们得到的答案是Person。

但实际上这个答案是错误的,这可能是某些严重缺陷的来源。

 

参考《JavaScript忍者秘籍》

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值