小编opi*_*pio的帖子

javascript原型继承 - 共享属性

我已将_data原型中的属性保存为所有已创建对象的定义.

 function A() {}
 A.prototype._data = [];
Run Code Online (Sandbox Code Playgroud)

现在所有创建的对象A都具有属性_data.

我想原型继承,原型中_data的原型将包含_data原型链中所有原型的值.

不知道直接的方式,在这个例子中我使用了一个getter get().

 function A() {}

 A.prototype._data = [];

 A.prototype.add = function(rec) {
   this.__proto__._data.push(rec);
 }

 A.prototype.get = function() {
   if(typeof this.__proto__.constructor.prototype.get == 'function')
   {
     return this.__proto__.constructor.prototype.get().concat(this.__proto__._data);
   }
   else
   {
     return this.__proto__._data || [];
   }
 }

 function B() {}
 B.prototype = Object.create(A.prototype, { constructor: { value: B }});
 B.prototype._data = [];
Run Code Online (Sandbox Code Playgroud)

当我a使用值创建对象和带有值的aa对象b时bb,b.get()返回 …

javascript inheritance prototype

6
推荐指数
1
解决办法
1774
查看次数

标签 统计

inheritance ×1

javascript ×1

prototype ×1