JavaScript- create object pattern 1.jpg
创建对象的3中方式
factory pattern
var peopleFactory = function(name, age){
var temp = {}
temp.name = name
temp.age = age
temp.printPerson = function () {
console.log(this.name + ',' + this.age)
}
return temp
}
var person1 = peopleFactory('张三','27')
person1.printPerson()
constructor pattern
var peopleConstructor = function (name, age) {
this.name = name
this.age = age
this.printPerson = function () {
console.log(this.name + ',' + this.age)
}
}
var person2 = new peopleConstructor('李四','18')
person2.printPerson()
new 关键字帮我们做了几件事情
- 1 创建了一个空对象temp
- 2 将这个空对象与this关联
- 3 将空对象的原型指向了构造函数的原型对象
方式缺点:每个person对象都有一个完全一样的方法printPerson,如果要创建成千上万个person对象,内存会被大量占用
prototype pattern
var peopleProto = function (name, age) {
this.name = name
this.age = age
}
peopleProto.prototype.printPerson = function () {
console.log(this.name + ',' + this.age)
}
var person3 = new peopleProto('王五','16')
person3.printPerson()
每一个构造函数都有一个称为原型的共享空间,用于保存公共属性和方法
我们把printPerson方法放到peopleProto这个构造函数的prototype中,
所有通过 new peopleProto() 创建的实例对象都能访问这个方法,避免了内存消耗
网友评论