工厂模式:
function createPerson(name, age, job) {let o = new Object();o.name = name;o.age = age;o.job = job;o.sayName = function() {console.log(this.name);};return o;}let person1 = createPerson("Nicholas", 29, "Software Engineer");let person2 = createPerson("Greg", 27, "Doctor");
特点:这种工厂模式虽然可以解决创建多个类似对象的问题,但没有解决对象标识问题(即新创建的对象是什么类型)。
构造器模式:
function Person(name, age, job){this.name = name;this.age = age;this.job = job;this.sayName = function() {console.log(this.name);};}let person1 = new Person("Nicholas", 29, "Software Engineer");let person2 = new Person("Greg", 27, "Doctor");person1.sayName(); // Nicholasperson2.sayName(); // Greg
要创建Person 的实例,应使用new 操作符。以这种方式调用构造函数会执行如下操作。
(1) 在内存中创建一个新对象。
(2) 这个新对象内部的[[Prototype]]特性被赋值为构造函数的prototype 属性。
(3) 构造函数内部的this 被赋值为这个新对象(即this 指向新对象)。
(4) 执行构造函数内部的代码(给新对象添加属性)。
(5) 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象。
原型模式:
function Person() {}Person.prototype.name = "Nicholas";Person.prototype.age = 29;Person.prototype.job = "Software Engineer";Person.prototype.sayName = function() {console.log(this.name);};let person1 = new Person();person1.sayName(); // "Nicholas"let person2 = new Person();person2.sayName(); // "Nicholas"console.log(person1.sayName == person2.sayName); // true
