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.
- You define the class for Car. That creates a constructor named
Carand creates a prototype for that class. - You define the
sayHi()method in the class definition. That adds thesayHimethod to the Car prototype. - You define the class for Bird. That creates a constructor named
Birdand creates a prototype for that class. - You create an instance of each class. That creates an object, assigns the corresponding prototype and runs the constructor (if there is one).
- You execute
bird.sayHi = car.sayHi;. That has two parts. First, it readscar.sayHi. Since there is no own property namedsayHion thecarobject, the interpreter checks the prototype chain for that object and finds thesayHimethod on the prototype. Then, it takes that method that it found and assigns it to thebirdobject as an own property (a property directly on thebirdobject. 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). - Then, you execute
bird.sayHi(). That causes the interpreter to look on thebirdobject for an own property namedsayHiand it finds the one that you just assigned. It grabs that method and executes it and you get your output in the console.
