我想在JavaScript中扩展Array对象,添加一些用户友好的方法,例如使用Array.Add()代替Array.push()等。
我实现了三种方法来做到这一点。不幸的是,第三种方法没有起作用,我想问为什么?以及如何让它工作。
//------------- 1st way
Array.prototype.Add=function(element){
this.push(element);
};
var list1 = new Array();
list1.Add("Hello world");
alert(list1[0]);
//------------- 2nd way
function Array2 () {
//some other properties and methods
};
Array2.prototype = new Array;
Array2.prototype.Add = function(element){
this.push(element);
};
var list2 = new Array2;
list2.Add(123);
alert(list2[0]);
//------------- 3rd way
function Array3 () {
this.prototype = new Array;
this.Add = function(element){
this.push(element);
};
};
var list3 = new Array3;
list3.Add(456); //push is not a function
alert(list3[0]); // undefined
在第三种方法中,我想在Array3类内部扩展Array对象。 如何做到这一点,以免出现“push不是一个函数”和“undefined”?
这里我添加了第四种方法。
//------------- 4th way
function Array4 () {
//some other properties and methods
this.Add = function(element){
this.push(element);
};
};
Array4.prototype = new Array();
var list4 = new Array4();
list4.Add(789);
alert(list4[0]);
我又不得不使用 prototype 了。 我希望避免在类构造函数之外使用额外的行,如 Array4.prototype。 我想要一个紧凑定义的类,所有部分都在一个地方。 但我认为我别无选择。
Array.prototype.add = Array.prototype.push;
- trusktr