【问题标题】:Property inheritance involving objects and prototypes涉及对象和原型的属性继承
【发布时间】:2018-11-21 08:05:37
【问题描述】:

我是 JS 的新手,在我的一个测试中,我一直试图弄清楚以下代码在属性继承方面是如何工作的。

function doSomething(){}

doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype
let anInstance = new doSomething();
anInstance.prop = "value"; //Add "prop" property to object "anInstance"
doSomething.prop = "another value"; //Add "prop" property to "doSomething"
let anotherInstance = new doSomething();

console.log(doSomething.prop);
console.log(anInstance);
console.log(anotherInstance.prop);

这是上面脚本在控制台中的输出:

another value

doSomething{prop: "value"}
  prop: "value"
  __proto__:
    foo: "bar"
    constructor: ƒ doSomething()
    __proto__: Object

undefined

如您所见,将doSomethingprop 属性添加到其中后打印会返回预期的another value,但访问anotherInstanceprop 会返回undefined

anotherInstance 不是应该“继承”此类 prop 属性,因为它是在创建它的函数中定义的吗?

提前致谢。

【问题讨论】:

    标签: javascript inheritance properties prototype


    【解决方案1】:

    向函数添加属性与向函数的原型对象添加属性不同。函数的实例继承函数的prototype 属性,而不是函数自己的属性:

    function doSomething(){}
    
    doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype
    
    doSomething.prop = "another value"; //Add "prop" property to "doSomething" but no the prototype
    
    let anotherInstance = new doSomething();
    
    // only has foo:
    console.log(doSomething.prototype)
    
    // this is the object it will inherit from
    // only has foo
    console.log(Object.getPrototypeOf(anotherInstance))
    
    //they are the same object:
    console.log(doSomething.prototype === Object.getPrototypeOf(anotherInstance))

    上面的代码中doSomething.prop只是函数的一个属性,对原型继承没有任何作用。

    【讨论】:

    • 谢谢,我现在更清楚了。但是我仍然不明白为什么不能直接将新属性添加到构造函数中,正如here“向构造函数中添加属性”一节中所解释的那样我>;给出的解释是"This way object properties can have default values."。您说过只有原型在继承中起作用。但是为什么?仅仅通过Constructor.prop = "value"向构造函数添加具有默认值的属性不是更简单直接吗?
    • 是的@JaxLogan - 如果您来自传统的 oop 语言,javascript 中的原型继承总是不寻常且令人沮丧。许多人会告诉你,“继承”实际上并不是 JS 所做工作的正确名称。您链接的文章是将道具添加到构造函数内的this,而不是直接添加到构造函数。
    • 啊,我明白了。然后我猜你不能向构造函数添加新属性,因为你需要this 这样做,指的是调用函数时创建的任何 instance 。所以你可以做person.newProp = "magic",因为它是一个已经创建的对象,但是要使用Person构造函数做类似的事情,你必须将newProperty添加到它的原型中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多