Reputation: 63
I was learning classes in JS and if you look at the code below
class Car{
drive(speed) {
console.log('Drive at '+ speed)
}
}
const car1 = new Car();
I defined function drive()
inside class Car and it is clear that drive()
is automatically attached to Car.prototype which ensures there is one copy of drive()
and the question is if we create new instance of Car class then Is drive() copied to car1
, if not, how is it possible to have one copy of drive()
and by passing argument get different results.
Upvotes: 0
Views: 127
Reputation: 2684
That's kind of confusion is for adding so much "sugar" to our classes without to know what it is happening.
Your class is defined using ES6
class Car {
drive(speed) {
console.log('Drive at ' + speed)
}
}
Next what you do is construct an object using your class, using new
The first question is what the new keyword does?
Car
prototypeSo, by doing const car1 = new Car();
, you get a new object wherein its prototype you get the drive
function.
In ES5 your class is written by using a constructor function.
function Car() {}
Car.prototype.drive = function (speed) { console.log(speed); }
Now, you can do: console.log(Car.prototype.constructor);
and you will see that the constructor function shown is Car.
If you want to create a subclass in ES6 you use the extends keyword but in ES5 what is really happening is:
Function SuperFastCar() {}
SuperFastCar.prototype = Object.create(Car.prototype);
SuperFastCar.prototype.turbo = function (maxSpeed) { console.log(maxSpeed); }
SuperFastCar.prototype.constructor = SuperFastCar;
Object.create
creates a new object using as the prototype the provided object. Also, we need to overwrite the constructor
, if not Car
constructor function will appear for SuperFastCar
.
Upvotes: 1
Reputation: 6325
Everything you create inside the prototype
will be shared between all instances of the class. Keep in mind that in the methods you define inside the prototype
you are typically defining the behaviour of your class (which should be shared between all instances).
Now, when you define a second instance of your Car
class, both the first and the second instance share the drive
method. But that doesn't mean that they can not call the method with different values:
class Car {
drive(speed) {
console.log('Drive at '+ speed)
}
}
const car1 = new Car();
car1.drive('10mph'); // ---> Will log "Drive at 10mph"
const car2 = new Car();
car2.drive('15mph'); // ---> Will log "Drive at 15mph"
Upvotes: 0
Reputation: 37755
Yes is it available on instance of Car class
, You can pass value when invoking drive
function on any instance of Car
class
class Car {
drive(speed) {
console.log('Drive at ' + speed)
}
}
const car1 = new Car();
car1.drive('50 kmph')
Upvotes: 1