Where are the properties stored in prototypes are saved?

时间:2017-12-18 06:40:02

标签: javascript object properties prototype

if an object instance is created so the property defined with its prototype will not be attached to this instance until we define a value for the prototype property.

My question is where are the prototype properties of any instance are stored? And if those properties are stored in the same instance then what would be the advantage of using the prototype as it consumes the same memory space?

1 个答案:

答案 0 :(得分:0)

  

我的问题是任何实例的原型属性在哪里   存储在哪里?如果这些属性存储在同一个实例中,那么   使用原型会有什么好处,因为它消耗了原型   相同的记忆空间?

Tl,博士

父对象

原型属性继承,因此它们不存储在个别实例中相同。

这些单个实例保留对原型属性的引用,这样如果 prototype的属性发生更改,则会在每个实例中反映出来。 实例对象

示例

让我们举一个对象的例子。

var obj = function(){};

将属性a1添加到obj

obj.prototype.a1 = 1;

创建childObj1的子实例obj并检查原型属性是否被继承。

var childObj1 = new obj();
console.log( childObj1 ); //show a1

创建a2的另一个属性obj,并检查是否继承了原型属性。

obj.prototype.a2 = 2;
console.log( childObj1 ); //show a1 and a2

创建childObj2的另一个子实例obj,并检查原型属性是否被继承。

var childObj2 = new obj();
console.log( childObj2 ); //show a1 and a2

obj.prototype.a3 = 3;
console.log( childObj1 ); //show a1, a2 and a3
console.log( childObj2 ); //show a1, a2 and a3

var obj = function(){};

obj.prototype.a1 = 1;

var childObj1 = new obj();
console.log( childObj1 ); //show a1

obj.prototype.a2 = 2;
console.log( childObj1 ); //show a1 and a2

var childObj2 = new obj();
console.log( childObj2 ); //show a1 and a2

obj.prototype.a3 = 3;
console.log( childObj1 ); //show a1, a2 and a3
console.log( childObj2 ); //show a1, a2 and a3