JS new 操作符的过程

2017-04-25  本文已影响0人  2e69fbf9f4d7
var  Color = function(color){
    this.color  = color
};
Color.prototype ={
    show : function(){
          console.log(this.color)
  }
};
new Color("red");
console.log(new Color("red"));
console.dir(new Color("red"));

new 实例化一个函数,其内部模拟大致如下:

new Color("red") = function(){
    /*===1===*/
    var obj = {};
    obj.__proto__ =  Color.prototype;
  /*===2===*/
  var result = Color.call(obj,"red");
  /*===3===*/
return  typeof  result  ==="object"?result:obj;
}

上一篇 下一篇

猜你喜欢

热点阅读