javascript - 涉及对象和原型的属性继承
问题描述
我是 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
如您所见,printingdoSomething
的prop
属性在添加到它之后会返回 expected another value
,但访问anotherInstance
的会prop
返回undefined
。
这不anotherInstance
应该“继承”这样prop
的属性,因为它是在创建它的函数中定义的吗?
提前致谢。
解决方案
向函数添加属性与向函数的原型对象添加属性不同。函数的实例继承函数的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
中只是函数的一个属性,它在原型继承中没有任何作用。
推荐阅读
- jenkins - Jenkinsfile 脚本并行导致 shell 语句失败
- java - 使用反射为setter方法赋值
- c# - Microsoft Graph 错误响应 - 如何从 JSON 中提取 HTTP 状态代码和内部错误代码?
- r - 将文件路径作为字符串从数据框列传递给 readOGR 函数
- vuejs2 - v-bind vuejs 上的三元运算符真或假
- github - Github 中是否有一种方法可以使用 ui 来查找我正在审查的所有 Pull Request 或要求我审查的所有请求?
- android - 使用 joda 以分钟为单位显示时间间隔以显示在日历中
- angular - 角度 8 中的 youtube 数据 api v3 中的错误 401
- sql - 当用户在 RoR 中接收邮件时,查找具有今天日期的卡片
- django - 如何在 django 中添加对我的博客的访问次数