标签:javascript class closure prototype
// 模拟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);
本文出自 “Doerthous” 博客,请务必保留此出处http://doerthous.blog.51cto.com/11762533/1858936
标签:javascript class closure prototype
原文地址:http://doerthous.blog.51cto.com/11762533/1858936