是否可以创建对象数组的克隆?我不想扩展 Array 对象本身,因为我的特定方法不应该为我的应用程序的所有数组公开。只有一个特定的数组。
var Arr = function () {};
Arr.prototype = Object.create( Array.prototype );
Arr.prototype.push = function() {
// Some custom code here
Array.prototype.push.apply( this, arguments );
};
此示例使用方法运行良好,但如果我按字面意思设置值,则长度不会增加。因为 Arr 实际上是一个 Object。
var arr1 = new Arr();
arr1[1] = 13;
console.log(Object.prototype.toString.call( arr1 ), arr1, arr1.length); // [object Object] { '1': 13 } 0
var arr2 = new Array();
arr2[1] = 13;
console.log(Object.prototype.toString.call( arr2 ), arr2, arr2.length); // [object Array] [ , 13 ] 2
最佳答案
在 ES5 和更早版本中,您不能“子类化”Array
(即,基于 Array
构造函数和 Array 创建您自己的构造函数和原型(prototype).prototype
) 并正确处理魔术属性,但从 ES2015(又名“ES6”)开始,有几种不同的方式,最简单的是新的 class
东西:
// REQUIRES ES2015+!
class MyArray extends Array {
constructor(...args) {
super(...args);
}
lengthTimesTwo() {
return this.length * 2;
}
cappedJoin() {
return this.map((s) => s.toUpperCase()).join();
}
}
var a = new MyArray("one", "two", "three");
console.log("lengthTimesTwo: " + a.lengthTimesTwo());
console.log("cappedJoin: " + a.cappedJoin());
在 ES5 世界中,有许多障碍你可以跳过以真正接近,并且人们正在构建像 Babel 这样的转译器。做(如果你坚持使用 ES5 环境,你可能想使用 class
和 transpile),但大多数时候创建一个构建数组然后添加方法的函数就足够了该特定实例:
var arrayExtras = {
lengthTimesTwo: function() {
return this.length * 2;
},
cappedJoin: function() {
return this.map(function(s) {
return s.toUpperCase();
}).join();
}
//...and so on...
};
function myArray() {
var key, rv = [];
rv.push.apply(rv, arguments);
for (key in arrayExtras) {
Object.defineProperty(rv, key, { // Add the method as a non-enumerable property
value: arrayExtras[key],
writable: true
});
// For pre-ES5 support, change the call above to simply:
// rv[ley] = arrayExtras[key];
}
return rv;
}
var a = myArray("one", "two", "three");
console.log("lengthTimesTwo: " + a.lengthTimesTwo());
console.log("cappedJoin: " + a.cappedJoin());
关于javascript - 使用我的自定义方法创建对象数组的克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30095009/