晴明的博客园 GitHub      CodePen      CodeWars     

[js] new

var Vehicle = function (){
  this.price = 1000;
};

var v = new Vehicle();
v.price // 1000

new 执行构造函数,返回一个实例对象。
通过new命令,让构造函数Vehicle生成一个实例对象,保存在变量v中。
这个新生成的实例对象,从构造函数Vehicle继承了price属性。
在new命令执行时,构造函数内部的this,就代表了新生成的实例对象,
this.price表示实例对象有一个price属性,它的值是1000。

new命令本身就可以执行构造函数,所以后面的构造函数可以带括号,也可以不带括号。

执行步骤

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

构造函数内部,this指的是一个新生成的空对象,所有针对this的操作,都会发生在这个空对象上。
构造函数之所以叫“构造函数”,就是说这个函数的目的,就是操作一个空对象(即this对象),将其“构造”为需要的样子。

new的实现

function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ param1) {
  // 将 arguments 对象转为数组
  var args = [].slice.call(arguments);
  // 取出构造函数
  var constructor = args.shift();
  // 创建一个空对象,继承构造函数的 prototype 属性
  var context = Object.create(constructor.prototype);
  // 执行构造函数
  var result = constructor.apply(context, args);
  // 如果返回结果是对象,就直接返回,否则返回 context 对象
  return (typeof result === 'object' && result != null) ? result : context;
}

// 实例
var actor = _new(Person, '张三', 28);

不加new执行构造函数

var Vehicle = function (){
  this.price = 1000;
};

var v = Vehicle();
v.price
// Uncaught TypeError: Cannot read property 'price' of undefined

price
// 1000

构造函数就变成了普通函数,并不会生成实例对象。this这时代表全局对象。
price属性变成了全局变量,而变量v变成了undefined。

解决方法

1 use strict
在严格模式中,函数内部的this不能指向全局对象,默认等于undefined,导致不加new调用会报错(JavaScript不允许对undefined添加属性)。

function Fubar(foo, bar){
  'use strict';
  this._foo = foo;
  this._bar = bar;
}

Fubar()
// TypeError: Cannot set property '_foo' of undefined

2

function Fubar(foo, bar){
  if (!(this instanceof Fubar)) {
    return new Fubar(foo, bar);
  }

  this._foo = foo;
  this._bar = bar;
}

Fubar(1, 2)._foo // 1
(new Fubar(1, 2))._foo // 1

return

new命令总是返回一个对象,要么是实例对象,要么是return语句指定的对象。

如果构造函数内部有return语句,而且return后面跟着一个对象,new命令会返回return语句指定的对象;
否则,就会不管return语句,返回this对象。

var Vehicle = function () {
  this.price = 1000;
  return 1000;//new命令就会忽略这个return语句,返回“构造”后的this对象。
};

(new Vehicle()) === 1000
// false

构造函数Vehicle的return语句,返回的是一个新对象。
new命令会返回这个对象,而不是this对象。

var Vehicle = function (){
  this.price = 1000;

  return { price: 2000 };
};

(new Vehicle()).price
// 2000

如果对普通函数(内部没有this关键字的函数)使用new命令,则会返回一个空对象。

function getMessage() {
  return 'this is a message';
}

var msg = new getMessage();

msg // {}
typeof msg // "Object"

new.target

函数内部可以使用new.target属性。
如果当前函数是new命令调用,new.target指向当前函数,否则为undefined。

function f() {
  console.log(new.target === f);
}

f() // false
new f() // true
posted @ 2017-06-09 19:15  晴明桑  阅读(155)  评论(0编辑  收藏  举报