Skip to content
On this page

new操作符

new 操作符具体干了什么呢? new 一个对象的过程是:

  • 创建一个空对象;
  • 对新对象进行 [prototype] 绑定(即 son. __ proto __ =father.prototype );
  • 新对象和函数调用的 this 会绑定起来;
  • 执行构造函数中的方法;
  • 如果函数没有返回值则自动返回这个新对象。

手写一个new方法

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

function myNew(ctx, ...args){ //...args为ES6展开符,也可以使用arguments
    // 先用Oject创建一个空的对象
    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;
}

let son = myNew(father, 'Bob');
son.sayname();

Released under the MIT License.