js创建对象实例
早期版本:(创建对象)
var person = new Object(); person.name = 'zzl1011'; person.age = 28; person.job = 'PHP'; person.sayName = function (){ alert(this.name); }
后来:(工厂模式)
function createPerson(name,age,job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { alert(this.name); } return o; } var person1 = createPerson('zzl','28','php'); var person2 = createPerson('zheng','24','d'); person1.sayName(); //zzl person2.sayName(); //zheng
构造函数模式:
function createPerson(name,age,job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { alert(this.name); } } var person1 = createPerson('zzl','28','php'); var person2 = createPerson('zheng','24','d'); person1.sayName(); //zzl person2.sayName(); //zheng
好处:
1.没有显式的创建对象。
2.直接将属性和方法赋给this对象。
3.没有return语句