虽然Object构造函数或对象字面量都可以创建单个对象,但是这些方式有个明显的缺点:使用同一个接口创建很多对象,会产生大量重复的代码。为了解决这个问题,就可以使用工厂模式来创建对象。
在ECMAScript中是无法创建类的,开发人员就发明了一种函数,用函数来封装特定接口创建对象的细节。
function createPerson(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; sayName = function () { alert(this.name); }; return o; } var person1 = createPerson('zxj', 23, "Software Engineer"); var person2 = createPerson('sdf', 25, "Software Engineer");
function createPerson(name, age, job) { this.name = name; this.age = age; this.job = job; sayName = function () { alert(this.name); }; } var person1 = new Person('zxj', 23, "Software Engineer"); var person2 = new Person('sdf', 25, "Software Engineer");
alert(person1.constructor == Person); //true alert(person2.constructor == Person); //true
alert(person1 instanceof Object); //true alert(person1 instanceof Person); //true alert(person2 instanceof Object); //true alert(person2 instanceof Person); //true
// 当作构造函数 var person = new Person('zxj', 23, "Software Engineer"); person.sayName(); //zxj // 当作普通函数 Person('sdf', 25, "Software Engineer"); //添加到window window.sayName(); //saf // 在另一个对象的作用域中调用 var o = new Object(); Person.call(o, "qwe", 25, "Nurse"); o.sayName(); //qwe
alert(person1.sayName == person.sayName()); // false
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = sayName; } function sayName() { alert(this.name); }; var person1 = new Person('zxj', 23, "Software Engineer"); var person2 = new Person('sdf', 25, "Software Engineer");