新运算符如何在JavaScript中运行? [英] How does the new operator work in JavaScript?
问题描述
可能是最不被理解的JavaScript部分,站在原型链旁边。
Probably the least understood part of JavaScript, standing beside the prototype chain.
所以问题是:怎么做......
So the question is: how does...
new dataObj(args);
...实际创建一个对象,并定义其原型链/构造函数/等?
...actually create an object, and define its prototype chain/constructors/etc?
最好显示一个替代方案,以完全理解这个关键字。
Best is to show an alternative, to fully understand this keyword.
推荐答案
new
运算符使用内部 [[Construct]]
方法,它基本上执行以下操作:
The new
operator uses the internal [[Construct]]
method, and it basically does the following:
- 初始化a新原生对象
- 设置此对象的内部
[[Prototype]]
,指向Function原型
属性。
- 如果函数的
prototype
属性不是对象(原始值,例如Number,改为使用String,Boolean,Undefined或Null),Object.prototype
。
- Initializes a new native object
- Sets the internal
[[Prototype]]
of this object, pointing to the Functionprototype
property.- If the function's
prototype
property is not an object (a primitive values, such as a Number, String, Boolean, Undefined or Null),Object.prototype
is used instead.
new
运算符的等效实现可以这样表达(假设ECMAScript 5Object.create
方法可用):An equivalent implementation of what the
new
operator does, can be expressed like this (assuming that the ECMAScript 5Object.create
method is available):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
这篇关于新运算符如何在JavaScript中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- If the function's
- 如果函数的