JavaScript手写new方法

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

function father(name){ this.name=name; this.sayname=function(){ console.log(this.name) } } var son=new father('kimi') dog.sayname();

输出结果:this

kimi

 

2.手写一个new方法spa

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();

输出结果:prototype

kimi

 

3.总结:code

new一个对象的过程是:对象

1>建立一个空对象blog

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

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

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

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

相关文章
相关标签/搜索