[Javascript] Understanding the .constructor property on JavaScript Objects

Constructor functions hold an interesting purpose in JavaScript. Unlike in classical languages, they do not always mean created by. In this lesson we’ll use the new keyword to make a constructor call and work with the .constructor property.

 

When we define a function:

function Foo(){
    //.
}

It has one prototype prop defined which is constructor. And it points to the Foo function itself.

console.log(Foo.prototype.constructor === Foo) // true

 

And if we have an instance created by new keyword:

const f= new Foo();

Then:

console.log(f.constructor === Foo) // true

 

So which mean:

f.constructor === Foo.prototype.constructor

 

This prototype chain can be broken when we reassgin the Foo.prototype = {}:

Foo.prototype = {}; // now we reassign to an empty object.
console.log(Foo.prototype.constructor === Foo);  // false
console.log(f.constructor === Foo); //true
console.log(f.constructor === Foo.prototype.constructor); // false

 

We can use Object.defineProperty to reassign the constructor to the Foo.prototype:

Foo.prototype = {};
Object.defineProperty(Foo.prototype, "constructor", {
  enumerable: false,
  writable: true,
  configurable: true,
  value: Foo
});

console.log(Foo.prototype.constructor === Foo); // true
console.log(f.constructor === Foo); // true
console.log(f.constructor === Foo.prototype.constructor); // true

 

转载于:https://www.cnblogs.com/Answer1215/p/9816917.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值