很长一段时间看网上大神的JS代码特别吃力,那种面向对象的写法方式让人看得云里来雾里去。于是就研究了一下JS面向对象,由于是初学,就将自己在网上找到的资料整理一下,作为记忆。
js面向对象的5种写方法:(来自http://www.iteye.com/topic/434462)
首先 定义circle类,拥有成员变量r,常量PI和计算面积的成员函数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());
//第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 ) ); //第3种写法
var Circle = new Object();
Circle.PI = 3.14159;
Circle.Area = function( r ) {
return this.PI * r * r;
}
alert( Circle.Area( 1.0 ) ); //第4种写法
var Circle={
"PI":3.14159,
"area":function(r){
return this.PI * r * r;
}
};
alert( Circle.area(1.0) ); //第5种写法
var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this.PI;}");
alert( (new Circle()).area(1.0) ); 在第一种方法中用到了pretotype请看下一节js中的pretotype
原文地址:http://blog.csdn.net/li_li_lin/article/details/40114753