下面是一个简单的js对象:定义Circle类,拥有成员变量r,常量PI和计算面积的成员函数area(),常用为第一种和第三种。
1.工厂方式
var Circle = function() { var obj = new Object(); obj.PI = 3.14159; obj.area = function( r ) { return this.PI * r * r; } return obj; } var c = new Circle(); alert( c.area( 1.0 ) );
2.比较正规的写法
function Circle(r) { this.r = r; } Circle.PI = 3.14159; Circle.prototype.area = function() { return Circle.PI * this.r * this.r; } var c = new Circle(1.0); alert(c.area());
3.json写法
var Circle={ "PI":3.14159, "area":function(r){ return this.PI * r * r; } }; alert( Circle.area(1.0) );
4.有点变化,但是实质和第一种一样
var Circle=function(r){ this.r=r; } Circle.PI = 3.14159; Circle.prototype={ area:function(){ return this.r*this.r*Circle.PI; } } var obj=new Circle(1.0); alert(obj.area())
5.JSON写法的扩展
Circle.PI = 3.14159; 能够放入属性中写成this.PI=3.14159;
var show={ btn:$('.div1'), init:function(){ var that=this; alert(this); this.btn.click(function(){ that.change(); alert(this); }) }, change:function(){ this.btn.css({'background':'green'}); } } show.init();