1.工厂模式
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age =age;
o.sayName = function(){
alert(this.name)
};
return o;
}
var person1 = createPerson("Nieo",29,"Coder");
var person2 = createPerson("Huu",22,"student");
存在问题:无法知道一个对象的类型。
2.构造函数模式
function Person(name, age, job){
this.name = name;
this.age =age;
this.sayName = function(){
alert(this.name)
};
}
var person1 = new Person("Nieo",29,"Coder");
var person2 = new Person("Huu",22,"student");
注意,无return语句,
创建Person的新实例,要使用new操作符,
不使用new则可作为正常函数使用。
constructor最迟用来标识对象类型,现验证如下:
alert(person1.constructor == Person);//true
alert(person2.constructor == Person);//true
创建的对象同时是Object、Person的实例,验证如下:
alert(person1 instanceof Object);//true
alert(person2 instanceof Person);//true
alert(person1 instanceof Object);//true
alert(person2 instanceof Person);//true
以上,说明创建自定义的构造函数时,可以创建一种特定的类型,如Person,这一点优于工厂模式。
问题:创建对象实例时,也会多次创建Function的实例,
this.sayName = function(){alert(this.name)};即同于,
this.sayName = new Function(){alert(this.name)};
下面方法可以解决上面问题,但会失去封装性,可以通过原型模式解决。
{...this.sayName = sayName;...}
function sayName(){alert(this.name)}