前端面试之js总结之new操作符

前言

之前在复习的时候,经常使用的new忽然感觉到错愕,不适应,今天查了资料,自己简单实现了一下。

new命令的作用

function Person(name){
    console.log(this);
    this.name=name;
}
var child=new Person;
child instanceof Person;

由上面的代码可知道new操作符绑定了Person内部this关键字,执行了Person内部的代码,返回了一个对象。

new命令的原理

1.创建一个空对象,作为将要返回的对象实例。
2.将这个空对象的原型,指向构造函数的prototype属性。
3.将这个空对象赋值给函数内部的this关键字。
4.开始执行内部的代码。

new的简易实现

注意下面这种行为。

function Person(){
    return {"cc":"20"}
}
var child=new Person();//{cc:"20"}
function Person(){
    return null
}
var child=new Person();

根据上面的行为实现new操作符

function _new(constructor,params){
    var args=[].slice.call(arguments);//把arguments对象转为数组
    var constructor=args.shift();//取出构造函数
    var context=Object.create(constructor.prototype);//创建新的对象,并把对象的原型指向构造函数的原型对象
    var result=constructor.apply(context,args);//绑定this
    return (typeof result==='object'&&result!=null)?result:context;//返回对象
}
var actor=_new(Person,'cc',20);

资料来源

资料来源:构造函数与 new 命令
红宝书(第三版)

最后

Github求一波star

你可能感兴趣的:(前端面试之js总结之new操作符)