js面向对象精要——构造函数和原型对象

js面向对象精要——构造函数和原型对象

文章目录

  • js面向对象精要——构造函数和原型对象
    • 构造函数
      • 什么是构造函数
        • instanceof
    • 原型对象
        • [[Prototype]] 属性
      • 在构造函数中使用原型对象
      • 内建对象的原型对象

2019-6-8

构造函数

什么是构造函数

通过 new 关键字创建对象时调用的函数

一般首字母大写

构造函数允许使用一致的方式初始化实例

// 定义方式一
function Person(name) {
  this.name = name
  
  this.sayName = function() {
    console.log(this.name)
  }
}
// 定义方式二,通过 Object.definProperty()方法
function Person(name) {
  Object.definProperty(this, 'name', {
    get: function() {
      return name
    },
    set: function(newName) {
    	this.name = newName
  	},
    enumerable: true,
    configurable: true
  })
  
  this.sayName = function() {
    console.log(this.name)
  }
}

var person1 = new Person('Hello')

instanceof

使用 instanceof 检查对象类型

console.log(person1 instanceof Person)  // true

原型对象

  • 对象的 prototype 属性成为原型,原型也是一个对象,可以把原型对象看做对象的基类。

  • 每个函数都有一个名为 prototype 的属性

[[Prototype]] 属性

一个实例对象可通过内部属性 [[Prototype]] 跟踪其原型对象。

该属性指向该实例使用的原型对象的指针。

person1 的 [[Prototype]] -> Person.prototype

eg:

var object = {}
var prototype = Object.getPrototypeOf(Object) // 读取[[Prototype]]属性的值
console.log(prototype === Object.prototype) // true 

在构造函数中使用原型对象

每创建一个实例对象,都需要初始化一个对象,如果对象中有公用的方法,没理由要重复创建,浪费系统资源。

  • 函数被创建时,constructor 指向函数自身
var fn = function() {}

console.log(fn.prototype)
console.log(fn.prototype.constructor === fn)  // true
function Person(name) {
  this.name = name
}
Person.prototype.sayName = function() {
  console.log('name:' + this.name)
}

var person1 = new Person('Tom')
var person2 = new Person('Li')

console.log(person1.name) // Tom
console.log(person2.name) // Li

console.log(person1.sayName) // name:Tom
console.log(person2.sayName) // name:Li
function Person(name) {
  this.name = name
}

Person.prototype = {
  sayName: function() {
    console.log(this.name)
  }
}

使用字面量形式改写原型对象改变了构造函数的属性,因此 constructor 指向 Object 而不是 Person

手动重置 constructor 属性

Person.prototype = {
  constructor: Person,
  
  sayName: function() {
    console.log(this.name)
  }
}

内建对象的原型对象

例如给 Array.prototype 添加 sum 方法

Array.prototype.sum = function() {
  return this.reduce(function(previous, current) {
    return previous + current
  })
}

var numbers = [1,2,3]
var result = numbers.sum()

console.log(result) // 6

不建议在生产环境中这么做,破坏内置对象容易引发其他错误

应用场景: polyfill 兼容垫片

你可能感兴趣的:(JavaScript)