1.基于已有对象扩充其属性和方法
var Obj = new Object(); Obj.saysomething = function(){} Obj.name = "";
2.工厂方式
function fun2(){}function creatObject(parame){ var object = new Object(); //functionbody; object.f = function(){} object.f2 = fun2; return object; } var Obj1 = creatObject(parame); Obj1.f();Obj1.f2();
3.构造函数方式
funtion Obj(parame){ this.f1 = function(){} } var object = new Obj(parame); object.f1();
4.原型(“prototype”)方式
function obj(){}; obj.prototype.value1 = val;obj.prototype.value2 = new Array(); obj.prototype.fun = function(){}; var o = new obj(); obj.value1 = "";obj.value2.push(parame); obj.fun();
原型+构造函数方式:对象之间的属性互不干扰,各个对象间共享同一个方法
function Person() { this.username = new Array(); this.password = "123"; } Person.prototype.getInfo = function() { alert(this.username + ", " + this.password); } var p = new Person(); var p2 = new Person(); p.username.push("zhangsan"); p2.username.push("lisi"); p.getInfo(); p2.getInfo();
5.动态原型方式--每个对象拥有自己的属性
{ this.username = "zhangsan"; this.password = "123"; if(typeof Person.flag == "undefined") { //此块代码应该只在第一次调用的时候执行 alert("invoked"); Person.prototype.getInfo = function() { //这个方法定义在原型中,会被每一个对象所共同拥有 alert(this.username + ", " + this.password); } Person.flag = true;//第一次定义完之后,之后的对象就不需要再进来这块代码了 } } var p = new Person(); var p2 = new Person(); p.getInfo(); p2.getInfo();
http://www.cnblogs.com/mengdd/p/3697255.html
时间: 2024-10-25 13:29:52