function Rectangle()
{
this.width = 0;
this.height = 0;
this.area = function(){ return this.width * this.height;};
}
var o = new Object();
Rectangle.apply(o);
o.width = 10;
o.height = 20;
alert(o.area());调用apply时,o对象就是Rectangle函数中this的值,因而实现了属性的复制。
2.给类设置初始化函数
var Class = {
create : function(){
return function(){
this.initialize.apply(this,arguments);
}
}
}
//创建类
var Rectangle = Class.create();
Rectangle.prototype = {
initialize : function(width,height){
this.width = width;
this.height = height;
},
toString : function(){
return "width:" + this.width + "\r\n" + "height:" + this.height;
}
}
//实例化对象并初始化
var rectangle = new Rectangle(80,120);
alert(rectangle.toString());
评论(0)
暂无评论。