JavaScript 类定义常用方法(转)
1、对象直接量
1 var obj1 = { 2 v1 : "", 3 get_v1 : function() { 4 return this.v1; 5 }, 6 set_v1 : function(v) { 7 this.v1 = v; 8 } 9 };
2、定义函数对象
1 var Obj = function() { 2 var v1 = ""; 3 this.get_v1 = function() { 4 return this.v1; 5 }; 6 this.set_v1 = function(v) { 7 this.v1 = v; 8 } 9 };
3、原型继承
1 var Obj3 = new Function(); 2 Obj3.prototype = { 3 v1 : "", 4 get_v1 : function() { 5 return this.v1; 6 }, 7 set_v1 : function(v) { 8 this.v1 = v; 9 } 10 };
4、工厂模式
1 function loadObj() { 2 var tmp = new Object(); 3 tmp.v1 = ""; 4 tmp.get_v1 = function() { 5 return tmp.v1; 6 }; 7 tmp.set_v1 = function(v) { 8 tmp.v1 = v; 9 }; 10 return tmp; 11 }
调用实例:
1 obj1.set_v1('hello1'); 2 alert(obj1.get_v1()); 3 4 var obj2 = new Obj(); 5 obj2.set_v1('hello2'); 6 alert(obj2.get_v1()); 7 8 var obj3 = new Obj(); 9 obj3.set_v1('hello3'); 10 alert(obj3.get_v1()); 11 12 var obj4 = loadObj(); 13 obj4.set_v1('hello4'); 14 alert(obj4.get_v1()); 15 16 alert(obj1); 17 alert(obj2); 18 alert(obj3); 19 alert(obj4);
原文出自:http://www.cnblogs.com/xusir/archive/2013/01/17/2863882.html