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
Car
and creates a prototype for that class. - You define the
sayHi()
method in the class definition. That adds thesayHi
method to the Car prototype. - You define the class for Bird. That creates a constructor named
Bird
and 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 namedsayHi
on thecar
object, the interpreter checks the prototype chain for that object and finds thesayHi
method on the prototype. Then, it takes that method that it found and assigns it to thebird
object as an own property (a property directly on thebird
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). - Then, you execute
bird.sayHi()
. That causes the interpreter to look on thebird
object for an own property namedsayHi
and it finds the one that you just assigned. It grabs that method and executes it and you get your output in the console.