我意识到,严格来说,这不是数组类型的子类,但这会以人们可能期望的方式工作,还是我还会遇到.length之类的问题?如果正常的子类化是一个选项,那么我不会有任何缺点吗?
function Vector()
{
var vector = [];
vector.sum = function()
{
sum = 0.0;
for(i = 0; i < this.length; i++)
{
sum += this[i];
}
return sum;
}
return vector;
}
v = Vector();
v.push(1); v.push(2);
console.log(v.sum());
答案 0 :(得分:7)
我将一个数组包装在一个合适的矢量类型中,如下所示:
window.Vector = function Vector() {
this.data = [];
}
Vector.prototype.push = function push() {
Array.prototype.push.apply(this.data, arguments);
}
Vector.prototype.sum = function sum() {
for(var i = 0, s=0.0, len=this.data.length; i < len; s += this.data[i++]);
return s;
}
var vector1 = new Vector();
vector1.push(1); vector1.push(2);
console.log(vector1.sum());
或者,您可以在阵列上构建新的原型函数,然后只使用普通数组。
如果你一致命名数组所以它们都以小写v开头,例如类似的东西,它们清楚地标记了它们是矢量而不是普通数组,你在矢量特定的原型函数上做同样的事情,那么它应该很容易跟踪。
Array.prototype.vSum = function vSum() {
for(var i = 0, s=0.0, len=this.length; i < len; s += this[i++]);
return s;
}
var vector1 = [];
vector1.push(1); vector1.push(2);
console.log(vector1.vSum());
答案 1 :(得分:5)
编辑 - 我最初写道,你可以像任何其他对象一样子类化一个数组,这是错误的。每天学些新东西。这是一个很好的讨论
http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/
在这种情况下,作文会更好吗?即只需创建一个Vector对象,并让它由数组支持。这似乎是你所处的路径,你只需要将push和任何其他方法添加到原型中。
答案 2 :(得分:2)
包装器的另一个例子。和.bind一起玩。
var _Array = function _Array() {
if ( !( this instanceof _Array ) ) {
return new _Array();
};
};
_Array.prototype.push = function() {
var apContextBound = Array.prototype.push,
pushItAgainst = Function.prototype.apply.bind( apContextBound );
pushItAgainst( this, arguments );
};
_Array.prototype.pushPushItRealGood = function() {
var apContextBound = Array.prototype.push,
pushItAgainst = Function.prototype.apply.bind( apContextBound );
pushItAgainst( this, arguments );
};
_Array.prototype.typeof = (function() { return ( Object.prototype.toString.call( [] ) ); }());
答案 3 :(得分:0)
@hvgotcodes答案有awesome link。我只是想在这里总结一下结论。
Wrappers. Prototype chain injection
这似乎是从文章中扩展数组的最佳方法。
可以使用包装器...其中对象的原型链被扩充,而不是对象本身。
function SubArray() {
var arr = [ ];
arr.push.apply(arr, arguments);
arr.__proto__ = SubArray.prototype;
return arr;
}
SubArray.prototype = new Array;
// Add custom functions here to SubArray.prototype.
SubArray.prototype.last = function() {
return this[this.length - 1];
};
var sub = new SubArray(1, 2, 3);
sub instanceof SubArray; // true
sub instanceof Array; // true
对我来说不幸的是,这种方法使用了{8}中不支持的arr.__proto__
,这是我必须支持的浏览器。
Wrappers. Direct property injection.
此方法比上述方法慢一点,但适用于IE 8 - 。
包装器方法避免设置继承或模拟长度/索引关系。相反,类似工厂的函数可以创建一个普通的Array对象,然后使用任何自定义方法直接扩充它。由于返回的对象是数组1,它保持适当的长度/索引关系,以及“数组”的[[类]]。它自然也继承自Array.prototype。
function makeSubArray() {
var arr = [ ];
arr.push.apply(arr, arguments);
// Add custom functions here to arr.
arr.last = function() {
return this[this.length - 1];
};
return arr;
}
var sub = makeSubArray(1, 2, 3);
sub instanceof Array; // true
sub.length; // 3
sub.last(); // 3
答案 4 :(得分:0)
有一种看起来和感觉像原型继承的方式,但它只有一种方式不同。
首先让我们看看javascript中实现原型继承的standard ways之一:
var MyClass = function(bar){
this.foo = bar;
};
MyClass.prototype.awesomeMethod = function(){
alert("I'm awesome")
};
// extends MyClass
var MySubClass = function(bar){
MyClass.call(this, bar); // <- call super constructor
}
// which happens here
MySubClass.prototype = Object.create(MyClass.prototype); // prototype object with MyClass as its prototype
// allows us to still walk up the prototype chain as expected
Object.defineProperty(MySubClass.prototype, "constructor", {
enumerable: false, // this is merely a preference, but worth considering, it won't affect the inheritance aspect
value: MySubClass
});
// place extended/overridden methods here
MySubClass.prototype.superAwesomeMethod = function(){
alert("I'm super awesome!");
};
var testInstance = new MySubClass("hello");
alert(testInstance instanceof MyClass); // true
alert(testInstance instanceof MySubClass); // true
下一个例子只是包装上面的结构以保持一切清洁。乍一看似乎有一个微小的调整来表现奇迹。然而,所有真正发生的事情是子类的每个实例都不是使用Array原型作为构造的模板,而是使用Array的实例 - 所以子类的原型被挂钩到一个完全加载的对象的末尾。传递一个数组的ducktype - 然后复制它。如果你仍然在这里看到一些奇怪的东西而且它让你烦恼,我不确定我能否更好地解释它 - 所以它的工作原理可能是另一个问题的好主题。 :)
var extend = function(child, parent, optionalArgs){ //...
if(parent.toString() === "function "+parent.name+"() { [native code] }"){
optionalArgs = [parent].concat(Array.prototype.slice.call(arguments, 2));
child.prototype = Object.create(new parent.bind.apply(null, optionalArgs));
}else{
child.prototype = Object.create(parent.prototype);
}
Object.defineProperties(child.prototype, {
constructor: {enumerable: false, value: child},
_super_: {enumerable: false, value: parent} // merely for convenience (for future use), its not used here because our prototype is already constructed!
});
};
var Vector = (function(){
// we can extend Vector prototype here because functions are hoisted
// so it keeps the extend declaration close to the class declaration
// where we would expect to see it
extend(Vector, Array);
function Vector(){
// from here on out we are an instance of Array as well as an instance of Vector
// not needed here
// this._super_.call(this, arguments); // applies parent constructor (in this case Array, but we already did it during prototyping, so use this when extending your own classes)
// construct a Vector as needed from arguments
this.push.apply(this, arguments);
}
// just in case the prototype description warrants a closure
(function(){
var _Vector = this;
_Vector.sum = function sum(){
var i=0, s=0.0, l=this.length;
while(i<l){
s = s + this[i++];
}
return s;
};
}).call(Vector.prototype);
return Vector;
})();
var a = new Vector(1,2,3); // 1,2,3
var b = new Vector(4,5,6,7); // 4,5,6,7
alert(a instanceof Array && a instanceof Vector); // true
alert(a === b); // false
alert(a.length); // 3
alert(b.length); // 4
alert(a.sum()); // 6
alert(b.sum()); // 22
很快我们就会有类和能力扩展ES6中的本地课程,但这可能还有一年。与此同时,我希望这有助于某人。
答案 5 :(得分:0)
function SubArray(arrayToInitWith){
Array.call(this);
var subArrayInstance = this;
subArrayInstance.length = arrayToInitWith.length;
arrayToInitWith.forEach(function(e, i){
subArrayInstance[i] = e;
});
}
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.specialMethod = function(){alert("baz");};
var subclassedArray = new SubArray(["Some", "old", "values"]);
答案 6 :(得分:0)
There are many good ways all suggested here. Personally I think the best way to subclass an "Array" is not not subclass an actual Array but rather subclass an "Array-Like-Object". There are many of them out there, personally I use Collection.
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();
答案 7 :(得分:0)
现在你可以使用ES6类的子类:
class Vector extends Array {
sum(){
return this.reduce((total, value) => total + value)
}
}
let v2 = new Vector();
v2.push(1);
v2.push(2);
console.log(v2.sum())