美文网首页
js-分析new操作符的行为,并模拟

js-分析new操作符的行为,并模拟

作者: DoEmpty | 来源:发表于2020-04-27 16:43 被阅读0次

如下代码

function Student(name) {
  this.name=name;
}
let stu = new Student('kk');

分析得到的stu,发现执行new之后会得到一个对象;
通过this.name为对象分配了name属性;
stu的原型链__proto__指向了Student的prototype;
综上,new操作符会做以下事情

  • 执行函数,并生成一个对象
  • 在函数作用域内,将this指向生成的对象
  • 并为对象的作用域链指向函数的原型

由此模拟new操作符:

function newOp(ctor) {
    //如果传入参数不是一个构造函数则抛出
    if(!ctor instanceof Function) {    
        throw new Error('error ctor')
    }
    //生成一个原型链指向ctor.prototype的对象
    let obj = Object.create(ctor.prototype)
    //得到除stor以外的其他参数
    args = [].slice.call(arguments,1)
    //通过apply将this指向新生成的对象并执行ctor
    ctor.apply(obj,args)
    //返回生成的对象
    return obj
}

相关文章

网友评论

      本文标题:js-分析new操作符的行为,并模拟

      本文链接:https://www.haomeiwen.com/subject/cxhuwhtx.html