>  기사  >  웹 프론트엔드  >  Object.create와 new: 언제 JavaScript 상속에 어느 것을 사용해야 합니까?

Object.create와 new: 언제 JavaScript 상속에 어느 것을 사용해야 합니까?

Barbara Streisand
Barbara Streisand원래의
2024-11-15 12:06:03994검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.