JS new()

234 阅读1分钟

前提

构造函数也是函数,其唯一的区别就是调用方式不同,任何函数只要使用new操作符调用构造函数,而不使用new操作符调用的函数就是普通函数。

new() 构造函数执行的过程

  • 创建一个新的对象(遇到new的时候)
  • 将新对象的_proto_指向构造函数的prototype对象
  • 将构造函数的作用域赋给新的对象(也就是this就指向新对象)
  • 执行构造函数中的代码(为这个对象添加属性)
  • 返回新对象

正常的使用new方法

function Person(name){
   this.name = name;
   this.sayName = function(){
       console.log(this.name)
   }
}
var son = new Person('tom')
son.sayName() // tom

手写new方法

function _new(ctx,...args){ // ...args为ES6展开符,也可以使用arguments
   cosnt obj = new Object() // 先用Object创建一个空对象
   obj.__proto__ = ctx.prototype //新对象会被执行prototype连接
   const rel = ctx.call(obj,...args)// 新对象和函数调用的this绑定起来
   return rel instanceof Object ? rel : obj // 判断函数返回值如果是null或者是undefined则返回obj,否则返回rel
}

function Person(name){
   this.name = name;
   this.sayName = function(){
       console.log(this.name)
   }
}
var son = _new(Person,'tom')
son.sayName()  // tom