ReasonJun

javascript : prototype (2) (instance / prototype level function) 본문

Frontend/Javasciprt

javascript : prototype (2) (instance / prototype level function)

ReasonJun 2023. 6. 8. 00:39
728x90

In JavaScript, "instance-level functions" and "prototype-level functions" are two ways to define and access functions within objects. These concepts are related to the object's prototype chain and how functions are shared among instances of objects.

  1. Instance-Level Functions: Instance-level functions, also known as "own functions" or "own methods," are functions defined directly on an individual object. Each instance of an object has its own copy of instance-level functions.
function Car(make, model) {
  this.make = make;
  this.model = model;

  this.startEngine = function() {
    console.log("Engine started for", this.make, this.model);
  };
}

const myCar = new Car("Toyota", "Camry");
myCar.startEngine(); // Output: Engine started for Toyota Camry

In this example, the startEngine function is defined as an instance-level function within the Car constructor function. Each Car object created using the constructor will have its own copy of the startEngine function.

Instance-level functions can have access to instance-specific properties using the this keyword. However, since each object instance has its own copy of the function, it can result in increased memory usage if there are many instances.

  1. Prototype-Level Functions: Prototype-level functions, also known as "prototype methods," are functions defined on an object's prototype. These functions are shared among all instances of the object. When a prototype-level function is invoked, it is executed in the context of the calling instance.
function Car(make, model) {
  this.make = make;
  this.model = model;
}

Car.prototype.startEngine = function() {
  console.log("Engine started for", this.make, this.model);
};

const myCar = new Car("Toyota", "Camry");
myCar.startEngine(); // Output: Engine started for Toyota Camry

In this example, the startEngine function is defined on the Car.prototype. This means that all instances of Car share the same copy of the startEngine function. The function is accessed through the prototype chain when invoked on an object.

 

Prototype-level functions offer memory efficiency since the function is shared among instances. However, they can access instance-specific properties using the this keyword, as demonstrated in the example.

Using prototype-level functions is generally preferred over instance-level functions when defining methods in JavaScript objects, especially when memory usage is a concern or when you want to ensure consistency across instances.

 

It's important to note that JavaScript automatically looks up properties and functions on the prototype chain if they are not found directly on an object. This enables object inheritance and allows objects to share common functionality through the prototype chain.

 

728x90
Comments