Home > database >  javascript : Assign a method to another object without defining that method in second class body
javascript : Assign a method to another object without defining that method in second class body

Time:12-11

I found this code in mozila developer site:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#global_context]

class Car {
  sayHi() {
    console.log('Hello from car');
  }
}
        
class Bird {
         
}
        
const car = new Car();
const bird = new Bird();

bird.sayHi = car.sayHi;
bird.sayHi(); //Why it works?!!!

How and why the last line works without defining method in second class or inherit that method from Car class?

CodePudding user response:

Functions are first class objects.

Internally, car is an empty object with a prototype that has its sayHi property defined.

Then, with bird.sayHi = car.sayHi, you are setting the bird.sayHi property.

CodePudding user response:

Let's walk through what exactly happens here.

  1. You define the class for Car. That creates a constructor named Car and creates a prototype for that class.
  2. You define the sayHi() method in the class definition. That adds the sayHi method to the Car prototype.
  3. You define the class for Bird. That creates a constructor named Bird and creates a prototype for that class.
  4. You create an instance of each class. That creates an object, assigns the corresponding prototype and runs the constructor (if there is one).
  5. You execute bird.sayHi = car.sayHi;. That has two parts. First, it reads car.sayHi. Since there is no own property named sayHi on the car object, the interpreter checks the prototype chain for that object and finds the sayHi method on the prototype. Then, it takes that method that it found and assigns it to the bird object as an own property (a property directly on the bird object. Remember, a method is JUST a function that is stored on an object. You can grab that function off the object and use it like any other function (it may or may not work properly when removed from its original context - that depends upon what it does).
  6. Then, you execute bird.sayHi(). That causes the interpreter to look on the bird object for an own property named sayHi and it finds the one that you just assigned. It grabs that method and executes it and you get your output in the console.
  • Related