跨浏览器的方式来子类JavaScript Array并获取array[i]方法
Cross-browser way to subclass JavaScript Array and get the array[i] method?
很高兴得知这种基本上子类化JavaScript Array
(从链接复制的代码)的方法:
function SomeType() {
this.push(16);
}
SomeType.prototype = [];
SomeType.prototype.constructor = SomeType; // Make sure there are no unexpected results
console.log(new SomeType()); // Displays in console as [16]
但这还不完全完整。 有没有办法像这样伪造数组的子类并获取[]
方法?
var a = [];
a[3] = true;
console.log(a.length); //=> 4
var s = new SomeType();
s[3] = true;
console.log(s.length); //=> 1
这样,在执行 for 循环时,您仍然可以将其视为数组:
for (var i = 0; i < s.length; i++) {
var item = s[i];
}
仅适用于
带有__proto__
的浏览器(已弃用),因此它不是跨浏览器的:
var CustomArray = function ( ) {
var array = [ 16 ];
array.__proto__ = this.__proto__;
return array;
};
CustomArray.prototype = [];
CustomArray.prototype.constructor = CustomArray;
var array = new CustomArray( );
console.log( array instanceof Array ); // true
console.log( array instanceof CustomArray ); // true
array[ 3 ] = 42;
console.log( array.length ); // 4
我认为没有其他方法可以做到这一点。
我发现子类化"数组"的最佳方法不是子类化"数组",而是另一个"数组类对象",那里有很多,一种是使用集合。基本上,它完成了数组所做的一切(包括括号表示法),但是一个"自定义"原型,因此它可以很容易地被子类化,不像原生原型,原生原型在子类化时经常有问题。
http://codepen.io/dustinpoissant/pen/AXbjxm?editors=0011
var MySubArray = function(){
Collection.apply(this, arguments);
this.myCustomMethod = function(){
console.log("The second item is "+this[1]);
};
};
MySubArray.prototype = Object.create(Collection.prototype);
var msa = new MySubArray("Hello", "World");
msa[2] = "Third Item";
console.log(msa);
msa.myCustomMethod();
相关文章:
- 如何从〔object HTMLUListElement〕将UL从cookie获取到Array
- 从Angular Scope中的Array中获取所有对象
- Javascript数组:给定array[n],获取array[n*m]
- 从Node.js上的mysql结果JSON中获取一个Array值
- Array.protype.every()-获取falsy值元素
- Javascript Array 从特定索引获取偏移索引
- 获取 Array.forEach 函数的返回值
- 如何从 Array Javascript 获取对象
- 跨浏览器的方式来子类JavaScript Array并获取array[i]方法
- 如何在不使用 Array.filter() 的情况下从我的 JSON 对象中获取特定值
- 获取 array.filter 回调函数中的索引
- 获取 array.length 中的第一个数字
- 从Array结果中获取两个文件
- 当Array被casted到ArrayBuffer中时,我如何获取dataType
- Javascript-在不使用Array.prototype.filter的情况下,根据键值获取两个对象数组之间的差异
- 如何从ajax responseText中获取json/array到javascript数组
- 美元.获取JSON请求+填充并返回ARRAY
- 在Angularjs中从array中获取数据并传递给id
- 使用[. .new Set()]只获取基于内部Array
- JS: Push到array并更新select而不获取重复项