[英]How does the new operator work in JavaScript?
可能是 JavaScript 中最不為人知的部分,站在原型鏈旁邊。
那么問題來了:怎么...
new dataObj(args);
...實際上創建一個 object,並定義其原型鏈/構造函數/等?
最好是顯示一個替代方案,以完全理解這個關鍵字。
new
運算符使用內部的[[Construct]]
方法,它基本上做了以下工作:
[[Prototype]]
,指向 Function prototype
屬性。
prototype
屬性不是 object(原始值,例如數字、字符串、Boolean、未定義或 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
表達式new C(arg1, arg2)
:
假設 C 是 JavaScript function (否則會出現錯誤):
C
的“ prototype
”屬性的值。
prototype
for a function is an object (automatically created when the function is declared) with its prototype set to Object.prototype
and a constructor
property pointing back to the function C
.C
並將“ this
”設置為新的 object,並使用提供的 ZDBC16FB4CAA5BDA8EDDAZ77。C
返回 object,則此 ZA8CFDE6331BD59EB2AC96F8911C4B6 的結果為。 否則新創建的 object 是表達式的結果。 ECMAScript 5 中new
的替代方法是使用內置的Object.createObject
方法。
new C(arg1, arg2)
相當於:
var obj = Object.createObject(C.prototype);
C.apply(obj, [arg1, arg2]);
標准 JavaScript 不允許您顯式設置 object 的原型,因此Object.createObject
無法在語言本身中實現。 一些實現確實允許它通過非標准屬性 __proto__。 在這種情況下,可以像這樣模擬new C
:
var obj = {};
obj.__proto__ = C.prototype;
C.apply(obj, [arg1, arg2]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.