书:构造器模式

在经典面向对象编程语言中,Constructor是一种在内存中已分配给该对象的情况下,用于初始化新创建对象的特殊方法。 在JS中,几乎所有的东西都是对象——object构造器。

Object构造器用于创建特定类型的对象——准备好对象以备使用,同时接受构造器可以使用的参数,以在第一次创建对象时,设置成员属性和方法的值。

创建对象

let newObject = {}

// 或者

let newObject = new Object()

在Object构造器为特定的值创建对象封装,或者没有传递值时,它将创建一个空对象并返回它。

将键值赋值给一个对象的四种方法:

// 1
newObject.someKey = "Holle World"
var key = newObject.someKey

// 2
newObject["someKey"] = "Holle World"
var key = newObject["someKey"]

// 3
Object.defineProperty(newObject, "someKey", {
  value: "for more control of the property’s behavior",
  writable: true,
  enumerable: true,
  configurable: true
})

// 4
Object.definePropert(newObject, {
  "someKey": {
    value: "holle world",
    writable: true
  },
  "anotherKey": {
    value: "hahaha",
    writable: false
  }
})

// 可以用 1 和 2 中获取属性的方法获取3 和 4 的值
可以继承的对象:
// 创建司机对象,继承于person对象
var driver = Object.create(person)

// 为 driver 设置一些属性
defineProp(driver, "topSpeed", "100mph")

// 获取继承的属性
console.log(driver.dateOfBirth)

// 获取设置的 100mph
console.log(driver.topSpeed)

基本Constructor创建对象

JS不支持类的概念,但它确实支持与对象一起用于 constructor 函数。通过在构造器前面加 new 关键字,告诉 JS 像使用构造器一样实例化一个新对象,并且对象的成员有该函数定义。

在构造器内, this 引用新创建的对象。回顾对象创建,基本的构造器看起来可能是这样的:

function Car(model, year, miles) {
  this.model = model
  this.year = year
  this.miles = miles

  this.toString = function() {
    return this.model + "has done"  + this.miles + "miles"
  }
}

// 用法
let civic = new Car("Honda Civic", 2009, 20000)
let modeo = new Car("Honda Modeo", 2010, 9000)

console.log(civic.toString)
console.log(modeo.toString)

带有原型的constructor的对象

通过JS构造器创建对象后,新对象就会具有构造器原型的所有属性。

function Car(model, year, miles) {
  this.model = model
  this.year = year
  this.miles = miles

}

Car.prototype.toString = function() {
  return this.model + "has done"  + this.miles + "miles"
}

// 用法
let civic = new Car("Honda Civic", 2009, 20000)
let modeo = new Car("Honda Modeo", 2010, 9000)

console.log(civic.toString)
console.log(modeo.toString)
 
原文地址:https://www.cnblogs.com/houfee/p/10970742.html