function (name) { var obj = new Object() obj.name = name obj.getName = function() { console.log(this.name) } return obj }
var person1 = createPerson('jack')
function Person(name) { }
Person.prototype = { name: 'jack', getName: function() { console.log(this.name) } }
var person1 = new Person('jack')
缺点:重新了原型,丢失了 constructor 属性
原型模式优化
1 2 3 4 5 6 7 8 9 10 11 12
function Person(name) { }
Person.prototype = { constructor: Person, name: 'jack', getName: function() { console.log(this.name) } }
var person1 = new Person('jack')
优点: 实例可以通过 constructor 属性找到所属构造函数
缺点: 还是存在原型模式的缺点
组合模式(构造函数模式和原型模式结合)
1 2 3 4 5 6 7 8 9 10 11 12
function Person(name) { this.name = name }
Person.prototype = { constructor: Person, getName: function() { console.log(this.name) } }
var person1 = new Person('jack')
优点:该共享的共享,该私有的私有
寄生构造函数模式
1 2 3 4 5 6 7 8 9 10 11 12 13
function Person(name) { var obj = new Object() obj.name = name obj.getName = function () { console.log(this.name) }
return obj }
var person1 = new Person('jack'); console.log(person1 instanceof Person) console.log(person1 instanceof Object) // true