开发者

a question about inheritance of Array in javascript

开发者 https://www.devze.com 2023-02-19 10:45 出处:网络
function ClassA() { this.a=[]; 开发者_运维知识库this.aa=100; } function ClassB() { this.b=function(){return \"classbb\"};
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());

Why can't Array inherit ClassA and ClassB? Thanks.


That's not quite the way to make the Array.prototype inherit from your objects. It would overwrite Array.prototype, which isn't allowed obviously.

You can however extend the prototype of Array with the properties/methods of ClassA/ClassB like this:

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);

You can also:

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


The standard prohibits overwriting Array.prototype:

The initial value of Array.prototype is the Array prototype object (15.4.4).
This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

You can easily verify that browsers comply to this:

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

精彩评论

暂无评论...
验证码 换一张
取 消