new操作符的实现

JavaScript中的new操作符的原理

例子

1
2
3
4
5
6
function Person (name, age) {
this.name = name
this.age = age
}
const person1 = new Person('走花路的长颈鹿', 26)
console.log(person1) //Person{name:'走花路的长颈鹿',age:26}

先定义了一个构造函数Person,然后通过new操作符生成Person构造函数的一个实例并将其引用赋值给变量person1。然后控制台打印出person1的内容,可以看到该实例对象具有nameage属性,它们的值就是我们在调用构造函数时传入的值。

new关键字进行的操作

  1. 先创建一个空对象obj={}

  2. 将obj的__proto__原型指向构造函数Person的prototype原型对象,即obj.__proto__ = Person.prototype

  3. 将构造函数Person内部的this指向obj,然后执行构造函数Person()(也就是跟调用普通函数一样,只是此时函数的this为新创建的对象obj而已,就好像执行obj.Person()一样)

  4. 若构造函数没有返回非原始值(即不是引用类型的值),则返回该新建的对象obj(默认会添加return this)。否则,返回引用类型的值。

new操作符的执行过程

自己实现一个new操作符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function myNew (constr, ...args) {
// 1,2 创建一个对象obj,将obj的__proto__属性指向构造函数的原型对象
// 即实现:obj.__proto__ === constructor.prototype
var obj = Object.create(constr.prototype)
// 3.将constrc内部的this(即执行上下文)指向obj,并执行
var result = constr.apply(obj, args)
// 4\. 如果构造函数返回的是对象,则使用构造函数执行的结果。否则,返回新创建的对象
return result instanceof Object ? result : obj
}

// 使用的例子:
function Person(name, age){
this.name = name;
this.age = age;
}
const person1 = myNew(Person, 'Tom', 20)
console.log(person1)  // Person {name: "Tom", age: 20}

关键点

  1. 将新创建对象的原型链设置正确,这样我们才能使用原型链上的方法。

  2. 将新创建的对象作为构造函数执行的上下文,这样我们才能正确地进行一些初始化操作。


2021年7月1日补充

看一个例子

1
2
3
4
5
6
7
8
9
10
11
12
function Player(color) {
this.color = color
}
Player.prototype.start = function() {}

const white = new Player('white')
const black = new Player('black')

console.log(black.__proto__) // start()
console.log(Object.getPrototypeOf(black)) // start()
console.log(Player.prototype) // start()
console.log(Player.__proto__) // {}

根据反推可以写一下思路

  1. 一个继承自Player.prototype的新对象 p1/p2被创建
  2. p1.__proto__ === Player.prototypep1.__proto__指向Player.prototype
  3. 将this指向新创建的对象p1/p2
  4. 返回一个新对象:
    1. 如果构造函数没有显示的返回值,那么返回this
    2. 如果有显式的返回值,是基本类型,那么还是返回this
    3. 如果构造函数有显式的返回值,是对象类型,比如是{a:1},那么就返回{a:1}
      现在我们再来实现一个new指令的功能
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      function Player(name){
      this.name = name
      }

      function objectFactory() {
      let o = new Object()
      let FunctionConstructor = [].shift.call(arguments)
      o.__proto__ = FunctionConstructor.prototype
      let resultObj = FunctionConstructor.apply(o, arguments)
      return typeof resultObj === 'object' ? resultObj : o
      }
      const p1 = objectFactory(Player, '花鹿')
      console.log(p1) // 花鹿

      完~


new操作符的实现
https://zouhualu.github.io/20210619/new操作符的实现/
作者
花鹿
发布于
2021年6月19日
许可协议