首頁 > web前端 > js教程 > 主體

Object.create 與 new:何時使用 JavaScript 繼承?

Barbara Streisand
發布: 2024-11-15 12:06:03
原創
1000 人瀏覽過

Object.create vs. new: When to Use Which for JavaScript Inheritance?

JavaScript Inheritance: Object.create vs. new

In JavaScript, inheritance can be achieved through various methods. Two commonly discussed approaches are using the new keyword and Object.create. When exploring inheritance, the sheer number of available options can be daunting.

To clarify the most accepted way of achieving inheritance in JavaScript, let's explore the differences between Object.create and new.

Object.create

Object.create is used to create a new object that inherits from another object. It does not invoke the constructor function of the parent object. This is useful when you only want to create a new object that inherits specific properties and methods from a parent object.

const baseModel = {
  property1: "value1",
  method1: function() {}
};

const newModel = Object.create(baseModel);
登入後複製

In this example, newModel inherits the property1 and method1 from baseModel.

new

The new keyword calls the constructor function of a class or object and creates a new instance of that class or object. It invokes the constructor function and thus initializes the new object with specific properties and methods.

class BaseModel {
  constructor(property1) {
    this.property1 = property1;
  }

  method1() {}
}

const newModel = new BaseModel("value1");
登入後複製

In this example, newModel is an instance of the BaseModel class with the property1 initialized to "value1".

Choosing the Right Approach

The choice between Object.create and new depends on whether you need to create a new object that inherits properties and methods or invoke the constructor function of the parent object.

  • Use Object.create when you only want to create an object that inherits from another object without calling the constructor.
  • Use new when you need to create an instance of a class or object and invoke its constructor.

In the given scenario, you want to have a base object Model which you can extend with RestModel or LocalStorageModel. Using Object.create (or its shim) is the correct way because you do not want to create a new instance of Model and call its constructor.

RestModel.prototype = Object.create(Model.prototype);
登入後複製

If you want to call the Model constructor on RestModels, use call() or apply() instead:

function RestModel() {
    Model.call(this); // apply Model's constructor on the new object
    ...
}
登入後複製

以上是Object.create 與 new:何時使用 JavaScript 繼承?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板