我需要一个数组来存储一些几何数据。我想简单地继承Array对象,然后用一些新的函数扩展它,比如“height”和“width”(所有子元素的高度/宽度之和),但也有一些方便的方法,比如“insertAt”或“remove”。
在不修改原始Array对象(Array.prototype.myMethod)的情况下,最好的方法是什么?
在不修改原始Array对象(Array.prototype.myMethod)的情况下,最好的方法是什么?
您可以直接将更改混入到Array中,但考虑到它并不是每个数组都应该具有的内容,这可能不是最佳选择。因此,让我们从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
都是 JavaScript 中 new
操作符所做的事情的一部分。 只要您是编写构造函数的人,就没有必要过度思考它们。 - ZJRArray
或Object
。在这种情况下,您无法覆盖构造函数,但是使用prototype
仍然可以丰富这些对象。 (只是,结果发现,这种方式很容易让自己踩到陷阱)我不了解最新情况,但我想某些浏览器可能会将某些核心对象的丰富视为安全威胁。 - ZJRArray.prototype.height = function() {
//implementation of height
}