Why assign Something to Something.prototype.constructor?

假装没事ソ 提交于 2019-12-04 06:28:51

By default, every prototype has a constructor property that refers to the function that it "belongs" to.

function A() {
}

console.log(A.prototype.constructor === A); // true

If you overwrite a prototype in its entirety with an object literal or with some other constructed prototype, this constructor value will get wiped away and be left undefined or with some other value.

function A() {
}
A.prototype = {
    greeting: "Hello!"
};

console.log(A.prototype.constructor === A); // false

The prototype constructor property is not needed in order for the constructor to operate correctly, but people will often reassign prototype.constructor back to its initial value in order to maintain consistency, and that's what you are seeing for Lexer.

Consider:

function A() {
}

function B() {
}

B.prototype = Object.create(A.prototype);

var b = new B();

console.log(b.constructor === A); // true
console.log(b.constructor === B); // false

B.prototype.constructor = B;

console.log(b.constructor === A); // false
console.log(b.constructor === B); // true

One can only speculate as to why this was left out for HashMap. I doubt it was done for any good reason and may have just been an oversight.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!