如何在 JavaScript 中达到 Object.prototype

how working to Object.prototype in JavaScript

我看到了 JavaScript 的文档并且我读到了: Object.prototype 并且在文档中他们评论说:

The Object.prototype property represents the Object prototype object.

好的,我知道我可以用这种方式创建一个对象:

var o = new Object();

但是这是什么意思:

** 属性表示Object原型对象**

好的,我知道什么是对象:

The Object constructor creates an object wrapper.

我的问题是:

你这样说是什么意思:

The Object.prototype property represents the Object prototype object.

在研究的时候我也看到了关于原型的这个,这个原型术语和这个是一样的Object.prototype?:

object that provides shared properties for other objects

here I saw that

我希望我的问题不好只是我不明白这个词?

Javascript 使用 creational Prototype pattern。为简单起见,每次调用 new Object()Object.create 时,您都在技术上克隆原型对象。 Object.prototype 仅保留对原型对象的引用。

为什么这很重要?因为你放置在原型上的任何东西都会被克隆。如果你把函数放在原型上,你的 created/cloned 对象只是引用它,这是不同的,所以当你改变原型上的函数时,它会反映在所有创建的对象上。但是,如果您指定变量,它们的值将被克隆,因此您创建的每个对象都将拥有自己的值。

Objects中Javascript可以相互继承。这意味着如果我们得到一个继承了 parent object 的 object child,您可以通过 child 访问 parent 的所有属性:

const parent = { age: 37 };
const child = Object.create(parent); // child inherits parent
console.log(child.age); // 37

现在parent被称为child的原型。现在 Object.prototype 属性 是继承链中最高的 parent,在我们的例子中是:

child -> parent -> Object.prototype

所以每个 object(以及几乎所有其他东西)都继承自那个 属性。这意味着如果您向其中添加内容:

Object.prototype.test = "hey!";

所有children(一切)继承它:

console.log({}.test, 1..test, "test".test); // hey, hey, hey!