的
new操作者使用内部
[[Construct]]方法,它基本上具有下列功能:
- 初始化新的本机对象
- 设置
[[Prototype]]
此对象的内部,指向Functionprototype
属性。- 如果函数的
prototype
属性不是对象(则使用原始值,例如Number,String,Boolean,Undefined或Null)Object.prototype
。
- 如果函数的
- 创建对象后,它将调用该函数,并提供对象作为其
this
值。 - 如果被调用函数的返回值是原始值,则返回内部创建的对象。
- 否则,如果返回对象,则内部创建的对象将丢失。
new运算符的等效实现可以这样表示(假设ECMAscript 5
Object.create方法可用):
function NEW(f) { var obj, ret, proto; // Check if `f.prototype` is an object, not a primitive proto = Object(f.prototype) === f.prototype ? f.prototype : Object.prototype; // Create an object that inherits from `proto` obj = Object.create(proto); // Apply the function setting `obj` as the `this` value ret = f.apply(obj, Array.prototype.slice.call(arguments, 1)); if (Object(ret) === ret) { // the result is an object? return ret; } return obj;}// Example usage:function Foo (arg) { this.prop = arg;}Foo.prototype.inherited = 'baz';var obj = NEW(Foo, 'bar');obj.prop; // 'bar'obj.inherited; // 'baz'obj instanceof Foo // true


