JavaScript手写new方法

1.看一下正常使用的new方法

function father(name){
    this.name=name;
    this.sayname=function(){
        console.log(this.name)
    }
}

var son=new father('kimi')
dog.sayname();

输出结果:

kimi

2.手写一个new方法

function father(name){
    this.name=name;
    this.sayname=function(){
        console.log(this.name)
    }
}

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

var son=myNew(father,'kimi')
son.sayname();

输出结果:

kimi

3.总结:

new一个对象的过程是:

1>创建一个空对象

2>对新对象进行[prototype]绑定(即son._proto_=father.prototype)

3>新对象和函数调用的this会绑定起来

4>执行构造函数中的方法

5>如果函数没有返回值则自动返回这个新对象

猜你喜欢

转载自www.cnblogs.com/keyng/p/13211177.html