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())
Circle.PI = 3.14159; 能夠放入屬性中寫成this.PI=3.14159;
#常用為第一種和第三種
第三種寫法的擴展小實例
var show={ btn:$('.p1'), init:function(){ var that=this; alert(this); this.btn.click(function(){ that.change(); alert(this); }) }, change:function(){ this.btn.css({'background':'green'}); } } show.init();#####################################
以上是javascript幾種常見的物件導向程式碼寫法總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!