JavaScript解决constructor属性被覆盖的问题

60 篇文章 0 订阅
55 篇文章 1 订阅

为了实现 NinjaTestInherit继承Person,产生了这样的问题:当把NinjaTestInherit的原型设置为Person的实例对象后,我们丢失了原来在constructor中的NinjaTestInherit原型。如果我们不希望丢失constructor属性,constructor属性可用于确定用于创建对象实例的函数。

使用Object.defineProperty方法在 NinjaTestInherit.property对象上增加新的constructor属性。

console.log('----------------------解决constructor属性的问题----------------------');
function Person() {}
Person.prototype.dance = function () {}

function NinjaTestInherit() {}
NinjaTestInherit.prototype = new Person();

//定义一个新的不可枚举的constructor属性,属性值是 NinjaTestInherit
Object.defineProperty(NinjaTestInherit.prototype, "constructor",{
  enumerable: false,
  value: NinjaTestInherit,
  writable: true
});

var ninjaTestInherit = new  NinjaTestInherit();
//建立的ninjaTestInherit的constructor与NinjaTestInherit的联系
if (ninjaTestInherit.constructor === NinjaTestInherit) {
  console.log("Connection from ninjaTestInherit instances to NinjaTestInherit constructor reestablished!");
}

//在NinjaTestInherit.prototype上没有定义可枚举的属性
for(let prop in NinjaTestInherit.prototype) {
  if (prop === 'dance') {
    console.log("The only enumerable property is dance!");
  }
}

 

通过上述代码重新建立了ninjaTestInherit实例与NinjaTestInherit构造器之间的联系,所以可以确定ninjaTestInherit实例是通过NinjaTestInherit构造器创建的。此外,如果遍历NinjaTestInherit.proptype对象,可确保不会访问到constructor属性。

 

参考《JavaScript忍者秘籍》

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值