Reputation: 1286
I am wondering why in this piece of code, when I am trying to access the properties of the object that the garfield
is made of, in this case Cat
, I am getting undefined
:
function Cat(){
this.legs = 2;
this.species = 'cat';
};
Cat.prototype.makeSound = function() {
console.log(this.sound); // logs undefined
};
const garfield = Object.create(Cat);
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) // logs undefined
Shouldn't I be able to get down the prototype inheritance chain the access to those properties?
Upvotes: 1
Views: 48
Reputation: 961
In your example Object.create does not create a new instance of the class! It creates a function (because Cat
is a function and you pass function's prototype)!
Use new
to create a new instance
const garfield = new Cat();
console.log(garfield.legs);
or
function GarfieldLikeCat() {}
GarfieldLikeCat.prototype = Object.create(Cat.prototype);
GarfieldLikeCat.prototype.constructor = GarfieldLikeCat;
to get the classical inheritance (not a new instance!).
If you didn't use this.legs = 2;
, but instead Cat.prototype.legs = 2;
, you could use Object.create
to create a new instance
function Cat() {}
Cat.prototype.legs = 2;
const garfield = Object.create(Cat.prototype);
console.log(garfield.legs);
Upvotes: 2
Reputation: 10906
The word OOP
contains "object" in its definition; meaning that you are dealing with objects.
Javascript does something special that it exposes the objects directly, in which you can use them without abstractions (without classes).
To create an object, you can just declare it with {}
. no need to create a class to get one like in java
for example.
To use Inheritance directly, you need to have an object, and append things to its prototype.
Here is an example:
const Cat = {
legs: 2,
species: 'cat',
};
Object.setPrototypeOf(Cat, {
makeSound() {
console.log(this.sound); // logs undefined
}
})
const garfield = Object.create(Cat);
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) //2
To use Inheritance using functions, you'd have to construct the function first to get the object out of the function (the this
) and the prototype will automatically be appended to the this
object.
function Cat(){
this.legs = 2;
this.species = 'cat';
};
Cat.prototype.makeSound = function() {
console.log(this.sound); // logs undefined
};
const garfield = new Cat();
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) // 2
Upvotes: 3