笔记 - JS构造函数与原型

82 阅读1分钟

Object.creat()

Syntax

Object.create(proto,[propertiesObject])
  • proto 新创建对象的原型对象。
  • propertiesObject 可选。需要传入一个对象,该对象的属性类型参照Object.defineProperties()的第二个参数。
  • 返回值:一个新对象
一个示例:

构造一个只有一个属性width的对象->square

let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
// 构造函数
function createSquare(width){ 
  // 以 squarePrototype 为原型创建空对象
  let obj = Object.create(squarePrototype)
  obj.width = width
  return obj
}
let squarePrototype = {
  getArea(){ 
    return this.width * this.width 
  },
  getLength(){
    return this.width * 4
  }
}
for(let i = 0; i<12; i++){
  squareList[i] = createSquare(widthList[i])
  // 这下创建 square 很简单了吧!
}

函数和原型结合
let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]

function createSquare(width){
  let obj = Object.create(createSquare.squarePrototype) // 先使用后定义?NO
  obj.width = width
  return obj
}
createSquare.squarePrototype = { //把原型放到函数上,结合够紧密了吗?
  getArea(){ 
    return this.width * this.width 
  },
  getLength(){
    return this.width * 4
  },
  constructor: createSquare //方便通过原型找到构造函数
}
for(let i = 0; i<12; i++){
  squareList[i] = createSquare(widthList[i])
  console.log(squareList[i].constructor) 
  // constructor 可以知道谁构造了这个对象 -> createSquare
}

new 操作符

let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
function Square(width){ 
  this.width = width
}
Square.prototype.getArea = function(){ 
  return this.width * this.width 
}
Square.prototype.getLength = function(){
  return this.width * 4
}
for(let i = 0; i<12; i++){
  squareList[i] = new Square(widthList[i])
  console.log(squareList[i].constructor)
}

prototype

对象.__proto__ === 其构造函数.prototype

唯一的例外:Object本身
Object.prototype.__proto__ === null