javascript中的new操作符经常用到,特别是在原型继承中。

new到底做了什么呢?

在ECMAScript 262中是这么解释的。

11.2.2 The new Operator
The production NewExpression : new NewExpression is evaluated as follows:
1. Let ref be the result of evaluating NewExpression.
2. Let constructor be GetValue(ref).
3. If Type(constructor) is not Object, throw a TypeError exception.
4. If constructor does not implement the [[Construct]] internal method, throw a TypeError exception.
5. Return the result of calling the [[Construct]] internal method on constructor, providing no arguments (that
is, an empty list of arguments).
The production MemberExpression : new MemberExpression Arguments is evaluated as follows:
1. Let ref be the result of evaluating MemberExpression.
2. Let constructor be GetValue(ref).
3. Let argList be the result of evaluating Arguments, producing an internal list of argument values (11.2.4).
4. If Type(constructor) is not Object, throw a TypeError exception.
5. If constructor does not implement the [[Construct]] internal method, throw a TypeError exception.
6. Return the result of calling the [[Construct]] internal method on constructor, providing the list argList as the
argument values.
大体的意思是,比如
<script>
var a=new b();
</script>
如果b不是object又或者b不存在[[Construct]]这个内部方法,就会抛出一个 TypeError异常,否则就执行b的 [[Construct]]方法,使这个方法的返回值 赋值给a
而[[Construct]]这个方法,虽然我们在JS中无法访问的到,但是引擎内部是可以访问到的。
<script>
var a=new “abc”;  //错误,字符串”abc”不是Object
var a=new {}; //错误,对象{}没有[[Construct]]方法。
</script>