JS中的 new 操作符简单理解

首先上一一个简单的 new 操作符实例


  1. var Person = function(name){
  2.     this.name = name;
  3.     this.say = function(){
  4.         return "I am " + this.name;
  5.     };
  6. }
  7. var nyf = new Person("nyf");
  8. nyf.say();
 
简单来说,上述例子中,以 new 操作符调用构造函数的时候,函数内部发生以下变化:
  1、创建一个空对象,并且 this 变量引用该对象,同时还继承了该函数的原型。
  2、属性和方法被加入到 this 引用的对象中。
  3、新创建的对象由 this 所引用,并且最后隐式的返回 this 。
 
以上情况在 new 操作符调用下,后台就相当于 

  1. var Person = function(name){
  2.     //var this = {};
  3.     this.name = name;
  4.     this.say = function(){
  5.         return "I am " + this.name;
  6.     };
  7.     //return this;
  8. }
对于以上的讲述不知道有没有讲清楚。
 

  1. var obj = new Base();
相当于运行以下代码

  1. var obj = {};
  2. obj.__proto__ = Base.prototype;
  3. Base.call(obj);
对于ES5中添加了 Object.create(),

  1. if(typeof Object.create !== "function"){
  2.     Object.create = function(o){
  3.         function F(){};
  4.         F.prototype = o;
  5.         return new F();
  6.     }
  7. }
http://blog.chinaunix.net/uid-26672038-id-3366869.html
原文地址:https://www.cnblogs.com/yuxinpeng/p/5993659.html