首頁  >  文章  >  web前端  >  JavaScript 中的 new 運算子如何運作,以及它如何使用原型鏈建立物件?

JavaScript 中的 new 運算子如何運作,以及它如何使用原型鏈建立物件?

Patricia Arquette
Patricia Arquette原創
2024-10-27 21:28:30194瀏覽

How does the `new` operator work in JavaScript, and how does it create objects with their prototype chains?

new 運算子在 JavaScript 中是如何運作的?

new 運算子在 JavaScript 的物件導向程式設計系統中扮演著舉足輕重的角色。了解其功能對於有效地建立和管理物件至關重要。

深入研究新運算符的實作

<code class="javascript">new dataObj(args);</code>

此程式碼片段利用內部[[ Construct]]方法來執行一系列特定操作:

  1. 物件建立:它初始化一個新的原生物件。
  2. 原型鏈建立: 該物件的內部 [[Prototype]] 設定為指向 Function 原型屬性。值得注意的是,如果 Function 原型屬性不是物件(原始值,例如 Number、String、Boolean、Undefined 或 Null),則使用 Object.prototype 作為原型。
  3. 函數呼叫: 建立物件後,呼叫函數,並將新建立的物件指派為其 this 值。
  4. 回傳值處理: 如果被呼叫函數的回傳值產生原語,傳回內部建立的物件。但是,如果傳回一個對象,則內部建立的對象將被丟棄。

清晰度的替代實現

為了增強理解,這裡有一個替代表示new 運算子實現的功能:

<code class="javascript">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</code>

在此範例中:

  • NEW 是模擬new 運算子行為的自訂函數。
  • 它檢查如果 Function 原型屬性是一個對象,則使用 Object.prototype 來建立新物件。
  • NEW 將函數套用到新建立的物件作為其 this 值。
  • 函數的回傳值決定最終要傳回的物件。

以上是JavaScript 中的 new 運算子如何運作,以及它如何使用原型鏈建立物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn