【问题标题】:is setting the 'constructor' property necessary for proper JS inheritance? [duplicate]是否设置正确的 JS 继承所需的“构造函数”属性? [复制]
【发布时间】:2012-11-24 13:44:48
【问题描述】:

可能重复:
Why is it necessary to set the prototype constructor?

我很难理解在构建层次结构时将 javascript 对象的“构造函数”属性设置为子类的必要性。我发现下面的代码在不更改构造函数属性的情况下完成了预期的操作,但在我发现的关于该主题的几乎所有参考资料中,构造函数都是明确设置的。我错过了什么吗? (我在 ECMAScript 规范中也没有发现任何明确使用它)。

A = function() {
    this.value = "a";

    this.A = function() {
        window.alert( this.value + " instanceof A : " + ( this instanceof A ) );
    }
}


B = function() {
    this.value = "b";

    this.B = function() {
        window.alert( this.value + " instanceof B : " + ( this instanceof B ) );
    }
}

B.prototype = new A();

test = function() {
    var b = new B();
    b.A();
    b.B();
}

【问题讨论】:

    标签: javascript inheritance properties constructor


    【解决方案1】:

    首先,正确的 JS 继承意味着将方法放入原型中:

    var A = function() {
        this.value = "a";
    };
    
    A.prototype.A  = function() {
            window.alert( this.value + " instanceof A : " + ( this instanceof A ) );
    };
    
    var B = function() {
        this.value = "b";
    };
    

    其次,建立原型链时不要运行构造函数:

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

    每当您重新分配整个.prototype 时,您就完全覆盖了该对象。所以构造函数 需要重新分配属性(如果要使用):

    B.prototype.constructor = B;
    
    B.prototype.B = function() {
        window.alert( this.value + " instanceof B : " + ( this instanceof B ) );
    };
    

    Object.create 在旧版浏览器中不受支持,但您可以执行以下操作:

    Object.create = Object.create || function( proto ) {
         if( proto == null ) {
             return {};
         }
         function f(){}
         f.prototype = proto;
         return new f();
    };
    

    【讨论】:

    • 只有在您的代码有使用它的期望时才需要设置constructor 属性。我个人觉得它完全没用。
    • @TimDown 不一定是你的代码,iirc,es5-shim 需要为getPrototypeOf设置构造函数属性
    • 那不是合适的垫片。
    • @TimDown 是的,我试图找到代码,现在它已被移动到 es5-sham.js :P 无论如何我已经编辑了它只有在要使用构造函数时才需要。跨度>
    • @Timdown,谢谢!我也是这么想的,但不确定。
    猜你喜欢
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    相关资源
    最近更新 更多