在构造函数中初始化的JavaScriptPrototype属性不会重写已分配的新原型

JavaScript Prototype properties initialized in constructor does not overrides with new prototype assigned

本文关键字:新原型 分配 重写 原型 构造函数 初始化 JavaScriptPrototype 属性      更新时间:2023-09-26

示例:

function ChildClass() {
    **ChildClass.prototype.Field1 = "Field1 value";**
}
ChildClass.prototype = {};
var childInstance = new ChildClass();
print(childInstance.Field1);

为什么我们仍然可以访问childInstance.Field1?

您的构造函数正在添加属性。当您调用构造函数来创建新实例时,该字段将添加到原型中。

因为您从构造函数内部对原型设置了该属性,该构造函数在ChildClass.prototype = {};之后运行。