javascript - 涉及对象和原型(prototype)的属性继承

标签 javascript inheritance properties prototype

我是 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 属性后返回预期的 另一个值,但访问 anotherInstanceprop 返回 undefined

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

提前致谢。

最佳答案

向函数添加属性与向函数的原型(prototype)对象添加属性不同。函数的实例继承函数的 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只是函数的一个属性,对原型(prototype)继承没有任何作用。

关于javascript - 涉及对象和原型(prototype)的属性继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53407615/

相关文章:

javascript - 函数未定义 C#

javascript - 将子组件的输出发送到父组件 - Angular 2

javascript - 动态访问.map数组函数中的对象属性

javascript - 未选中返回盒子上的属性(property)

javascript - 如何实现选中所有、取消选中和清除复选框列表的所有选项?

javascript - 同源策略的异常(exception)

.net - 以下场景的最佳设计模式

C++ 抽象类 - 添加所需的数据成员,还是只定义对其进行操作的方法?

c++ - 为什么需要这种明确的范围解析?

xml - 在 actionscript 中,检查 xml 节点属性是否存在的最佳方法是什么?