javascript - 对象的属性是否存储在其原型(prototype)中?

标签 javascript

MDN 文档说 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Inheriting_properties

When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

这是否意味着当将属性添加到对象时,它就会添加到其原型(prototype)中?

即。在下面的代码中

a = {};
a.foo = "hello";

实际上存储为

a.prototype.foo = "hello"

最佳答案

没有。如果将属性存储在对象上,则将其存储在对象上。

它说,当您尝试访问它(即读取它,而不是写入它)时,如果在对象上找不到它,它将查找它的原型(prototype)链。

const a = {};
const b = Object.create(a);

a.foo = "Foo";

console.log(b.foo);

关于javascript - 对象的属性是否存储在其原型(prototype)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58289677/

相关文章:

javascript - getElementsByTagName 没有改变颜色

javascript - Socket.io 无法与我的 Node/express 应用程序配合使用

javascript - 如何在对象值的异步 for 循环完成执行后调用函数

javascript - Node.js 网络抓取,在 URL 数组上循环

javascript - 让几个模块使用同一个mongo实例

javascript - 如果背景图片不存在,则在 Angular 中显示另一个背景

javascript - 10 秒后自动停止加载页面

javascript - 执行上下文是否有定义的名称将所有其他内容封装在 JavaScript 中?

javascript - Reactjs + webpack + babel 7 语法错误 : The rest element has to be the last element when destructing

javascript - 如何提交 html5 Canvas 作为表单发布的一部分?