javascript模拟类及类继承
·
// 模拟Class
function Rectangle(width, height){
this.height = height; // 实例变量(public)
this.getWidth = function(){ return width; } // 实例变量(private)
this.setWidth = function(w){ width = w; }
Rectangle.INSTANCE_COUNT++;
}
Rectangle.prototype.getSize = function(){ return { width:this.getWidth(), height:this.height } } // 实例方法
Rectangle.INSTANCE_COUNT = 0; // 类变量
Rectangle.getInstanceCount = function(){ return Rectangle.INSTANCE_COUNT; } // 类方法
var s = new Rectangle(15,15);
s.setWidth(50);
console.log(s, s.getSize(), Rectangle.getInstanceCount(), Rectangle.INSTANCE_COUNT);
// 继承
function PositionRectangle(width, height, x, y){
Rectangle.call(this, width, height); // 为this添加, width, height属性
this.x = x;
this.y = y;
this.getPosition = function(){ return { x: this.x, y: this.y } }
}
PositionRectangle.prototype = new Rectangle(); // 只继承方法
delete PositionRectangle.prototype.width;
delete PositionRectangle.prototype.height;
PositionRectangle.prototype.constructor = PositionRectangle; // 修正构造函数
s = new PositionRectangle(15,15,10,10);
console.log(s, s.getSize(), s.getPosition(), Rectangle.getInstanceCount(), Rectangle.INSTANCE_COUNT);转载于:https://blog.51cto.com/doerthous/1858936
更多推荐


所有评论(0)