JavaScript中new实现原理
1、创建一个空对象 obj
2、将该对象 obj 的原型链 __proto__ 指向构造函数的原型 prototype,
并且在原型链 __proto__ 上设置 构造函数 constructor 为要实例化的 Fn
3、传入参数,并让 构造函数 Fn 改变指向到 obj,并执行
4、最后返回 obj
例子:
构造函数
function Parent(age, name) { this.age = age this.name = name this.sayAge = function() { console.log('this.age :', this.age) } } Parent.prototype.sayName = function() { console.log('this.name :', this.name) }
模拟 new 运算符功能函数
function New(Fn) { let obj = {} let arg = Array.prototype.slice.call(arguments, 1) obj.__proto__ = Fn.prototype obj.__proto__.constructor = Fn Fn.apply(obj, arg) return obj }
测试
let son = new Parent(18, 'lining') let newSon = New(Parent, 18, 'lining') console.log('son :', son) // son : Parent { age: 18, name: 'lining', sayAge: [Function] } console.log('newSon :', newSon) // newSon : Parent { age: 18, name: 'lining', sayAge: [Function] } console.log('son.constructor :', son.constructor) // son.constructor : function Parent(age, name) { // this.age = age // this.name = name // this.sayAge = function() { // console.log('this.age :', this.age) // } // } console.log('newSon.constructor :', newSon.constructor) // newSon.constructor : function Parent(age, name) { // this.age = age // this.name = name // this.sayAge = function() { // console.log('this.age :', this.age) // } // }