Create Object Pattern

2018-11-03  本文已影响0人  dsying

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 关键字帮我们做了几件事情

方式缺点:每个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() 创建的实例对象都能访问这个方法,避免了内存消耗

上一篇下一篇

猜你喜欢

热点阅读