js 建立函數:js建立對象 對象如何繼承 及一些工具函數
來源:互聯網
上載者:User
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function () { return this.width * this.height; }; //類的執行個體方法 建議為原型對象定義方法而不是放在建構函式定義方法
Rectangle.prototype.toString = function () { return "[" + this.width + "," + this.height + "]"; };//這樣效能更好,所有的對象共用同一個方法,對象繼承之對象原型
function PositionRectangle(x, y, w, h) {
// Rectangle.apply(this, [w, h]); //調用父類的建構函式
this.superclass(w, h); //通過給原型追加屬性 調用父類的建構函式
this.x = x;
this.y = y;
}
PositionRectangle.prototype = new Rectangle();//子類的原型為超類的執行個體
PositionRectangle.prototype.superclass = Rectangle;//為原型添加屬性方便調用父類建構函式
PositionRectangle.prototype.constructor = PositionRectangle; //設定原型的constructor
delete PositionRectangle.prototype.width;//刪除超類建構函式在原型中建立的屬性
delete PositionRectangle.prototype.height; //刪除超類建構函式在原型中建立的屬性
PositionRectangle.prototype.contains = function (x, y) {
return (this.x < x && x < this.x + this.width, this.y < y && y < this.y + this.height);
}
PositionRectangle.prototype.toString = function () {
return "(" + this.x + "," + this.y + ")" + this.superclass.prototype.toString.apply(this);//調用父類的同名方法
};
function getPropertyName(/*object */o, /*option array*/r) {
var r = r [];
for (var name in o) {
r.push(name);
}
return r;
}
function copyProperties(/*object from*/from, /*object to*/to) {
var to = to {};
for (var p in from) {
to[p] = from[p];
}
return to;
}
function copyUndefinedProperties(/*object from*/from, /*object to*/to) {
for (var p in from) {
if (to[p] === undefined)
to[p] = from[p];
}
return to;
}
function filterArray(/*Array*/a, /*predicate*/predicate) { 本文連結http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20121116/33888.html