【问题标题】:a question about inheritance of Array in javascript关于javascript中数组继承的问题
【发布时间】:2011-03-25 07:15:48
【问题描述】:
function ClassA()  
{  
    this.a=[];
    this.aa=100;  
}  


function ClassB()  
{  
    this.b=function(){return "classbb"};  
}  
ClassB.prototype=new ClassA();  
Array.prototype= new ClassB();  
var array1= new Array();
alert(array1.b());

为什么Array不能继承ClassA和ClassB?谢谢。

【问题讨论】:

  • 我希望我们都同意这个问题是理论上的,因为如果你覆盖了它的原型,Array 将会变得毫无用处。

标签: javascript arrays inheritance


【解决方案1】:

这不是让 Array.prototype 从你的对象继承的方法。它会覆盖Array.prototype,这显然是不允许的。

但是,您可以使用 ClassA/ClassB 的属性/方法扩展 Array 的原型,如下所示:

function ClassA() {  
  this.a=[];
  this.aa=100;  
}  

function ClassB() {  
  this.b=function(){return "classbb"};  
}

ClassB.prototype = new ClassA; 

var instB = new ClassB;
for (var l in instB){
    Array.prototype[l] = instB[l];
}

var array1 = [];
alert(array1.aa);

您还可以:

Array.prototype.classb = new ClassB;
var array1 = [];
alert(array1.classb.aa);

【讨论】:

  • 谢谢。非常感谢您的帮助。
  • 我可以这样写吗?函数 ClassA() { this.a=[];这个.aa=100; } function ClassB() { this.b=function(){return "classbb"}; } ClassB.prototype = new ClassA; for (var l in ClassB.prototype){ Array.prototype[l] = ClassB.[l]; } var array1 = [];警报(array1.b);
  • 并非如此。首先,您需要分配 Classb.prototype[l](您在 for 循环中枚举)。其次,如果你这样做,你会错过ClassB.b,因为那不在ClassB 的原型中。如果您将方法 b 添加到 ClassB 的原型中,它将起作用。见jsfiddle.net/pgw9q
  • 你能告诉我为什么我这样写它仍然不起作用:function ClassA() { this.a=[];这个.aa=100; } 函数 ClassB() { } ClassB.prototype = new ClassA; ClassB.prototype.b=function(){return "classbb"}; for (var l in ClassB.prototype){ // console.log(l); Array.prototype[l] = ClassB.[l]; //我这里删除原型 } var array1 = [];警报(array1.b());
  • ClassB.[l] 应该是 ClassB.prototype[l]。 “我在这里删除原型”是什么意思?您的代码中没有任何内容被删除。
【解决方案2】:

The standard 禁止覆盖Array.prototype

Array.prototype 的初始值 是数组原型对象 (15.4.4).
该物业拥有 属性 { [[Writable]]: false, [[可枚举]]:假, [[可配置]]:假}。

您可以轻松验证浏览器是否符合此要求:

var origArrayProto = Array.prototype;
Array.prototype = new function () {}; // try to overwrite
alert(Array.prototype == origArrayProto); // true

【讨论】:

  • 非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 2013-02-15
  • 2012-10-20
  • 2011-06-12
  • 2022-10-01
  • 1970-01-01
  • 2011-08-01
相关资源
最近更新 更多