【发布时间】:2011-02-17 02:10:39
【问题描述】:
我需要一个数组来存储一些几何数据。我想简单地从 Array 对象继承,而不是用一些新的函数来扩展它,比如“height”和“width”(所有孩子的高度/宽度的总和),还有一些方便的方法,比如“insertAt”或“删除”。
不修改原始 Array 对象 (Array.prototype.myMethod) 的最佳方法是什么?
【问题讨论】:
标签: javascript arrays inheritance
我需要一个数组来存储一些几何数据。我想简单地从 Array 对象继承,而不是用一些新的函数来扩展它,比如“height”和“width”(所有孩子的高度/宽度的总和),还有一些方便的方法,比如“insertAt”或“删除”。
不修改原始 Array 对象 (Array.prototype.myMethod) 的最佳方法是什么?
【问题讨论】:
标签: javascript arrays inheritance
您始终可以将更改直接混合到数组中,但这可能不是最佳选择,因为它不是每个数组都应该具有的。所以让我们从 Array 继承:
// create a constructor for the class
function GeometricArray() {
this.width = 0;
this.height = 0;
}
// create a new instance for the prototype so you get all functionality
// from it without adding features directly to Array.
GeometricArray.prototype = new Array();
// add our special methods to the prototype
GeometricArray.prototype.insertAt = function() {
...
};
GeometricArray.prototype.remove = function {
...
};
GeometricArray.prototype.add = function( child ) {
this.push( child );
// todo calculate child widths/heights
};
【讨论】:
您是否(可能)将 Java 概念应用于 Javascript?
您不需要从 Javascript 中的类继承,您只需 丰富 个对象。
所以在我的世界(一个到处都是人头撞方法到对象的世界)中最好的方法是:
function GeometricArray()
{
var obj=[]
obj.height=function() {
// wibbly-wobbly heighty things
for(var i=0;i<this.length;i++) {
// ...
}
}
obj.width=function() {
// wibbly-wobbly widy things
// ...
}
// ...and on and on...
return obj
}
【讨论】:
prototype 和 this 都是 new 运算符在 javascript 中所做的事情的一部分。只要您是编写构造函数的人,这是一种过度思考,几乎没有存在的意义。
Array 或 Object。在这种情况下,您不能覆盖构造函数,但使用 prototype 无论如何您都可以丰富这些对象。 (只是,它出来了,这种方式真的很容易把自己打死)我不是最新的,但我想某些浏览器可能会将某些核心对象的丰富视为安全威胁
您可以使用原型设计将这些函数放入数组中。
要添加高度功能,例如这样做:
Array.prototype.height = function() {
//implementation of height
}
【讨论】: