当前位置: 代码迷 >> JavaScript >> JS 中面向对象的五种写法
  详细解决方案

JS 中面向对象的五种写法

热度:113   发布时间:2012-10-26 10:30:59.0
JS 中面向对象的5种写法

//定义Circle类,拥有成员变量r,常量PI和计算面积的成员函数area()

Java代码 复制代码
  1. //第1种写法??? ??
  2. function Circle(r) {??? ??
  3. ??????this.r = r;??? ??
  4. }??? ??
  5. Circle.PI = 3.14159;??? ??
  6. Circle.prototype.area = function() {??? ??
  7. ??return Circle.PI * this.r * this.r;??? ??
  8. }??? ??
  9. ?? ??
  10. var c = new Circle(1.0);?????? ??
  11. alert(c.area());?????
//第1种写法   
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());

?

Java代码 复制代码
  1. //第2种写法??? ??
  2. var Circle = function() {??? ??
  3. ??? var obj = new Object();??? ??
  4. ??? obj.PI = 3.14159;??? ??
  5. ?????? ??
  6. ??? obj.area = function( r ) {??? ??
  7. ???????return this.PI * r * r;??? ??
  8. ??? }??? ??
  9. ???return obj;??? ??
  10. }??? ??
  11. ?? ??
  12. var c = new Circle();??? ??
  13. alert( c.area( 1.0 ) );????
//第2种写法   
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 ) );

?

Java代码 复制代码
  1. //第3种写法??? ??
  2. var Circle = new Object();??? ??
  3. Circle.PI = 3.14159;??? ??
  4. Circle.Area = function( r ) {??? ??
  5. ???????return this.PI * r * r;??? ??
  6. }??? ??
  7. ?? ??
  8. alert( Circle.Area( 1.0 ) );????
//第3种写法   
var Circle = new Object();   
Circle.PI = 3.14159;   
Circle.Area = function( r ) {   
       return this.PI * r * r;   
}   
  
alert( Circle.Area( 1.0 ) );

?

Java代码 复制代码
  1. //第4种写法??? ??
  2. var Circle={??? ??
  3. ???"PI":3.14159,??? ??
  4. "area":function(r){??? ??
  5. ??????????return this.PI * r * r;??? ??
  6. ???????? }??? ??
  7. };??? ??
  8. alert( Circle.area(1.0) );????
//第4种写法   
var Circle={   
   "PI":3.14159,   
 "area":function(r){   
          return this.PI * r * r;   
        }   
};   
alert( Circle.area(1.0) );

?

Java代码 复制代码
  1. //第5种写法??? ??
  2. var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this.PI;}");??? ??
  3. ?? ??
  4. alert( (new Circle()).area(1.0) );????