I explore the deep end of JavaScript.
Well, let’s say I have a constructor function like this. Yes, I know this is a weird way of creating a constructor function, but …
JavaScript
x
4
1
function Animal(name){
2
return { name };
3
}
4
And I wanna add a prototype property like walk()
, but it doesn’t work here. I know it looks stupid, but…
JavaScript
1
4
1
Animal.prototype.walk = function () {
2
console.log(`${this.name} is walking ...`);
3
}
4
QUESTION: Is there any way that I can add this walk property as a prototype property?
Advertisement
Answer
If you have to explicitly return an object that isn’t this
in the constructor, then:
Create the prototype object outside, then use Object.create
inside the constructor:
JavaScript
1
10
10
1
const animalProto = {
2
walk() {
3
console.log(`${this.name} is walking ...`);
4
}
5
};
6
function Animal(name){
7
return Object.assign(Object.create(animalProto), { name });
8
}
9
const a = new Animal('foo');
10
a.walk();
But this is strange, can you do it the normal way and assign to a property of this
instead?
JavaScript
1
9
1
function Animal(name){
2
this.name = name;
3
}
4
Animal.prototype.walk = function () {
5
console.log(`${this.name} is walking ...`);
6
}
7
8
const a = new Animal('foo');
9
a.walk();
or if you want to avoid listing name
twice
JavaScript
1
9
1
function Animal(name){
2
Object.assign(this, { name });
3
}
4
Animal.prototype.walk = function () {
5
console.log(`${this.name} is walking ...`);
6
}
7
8
const a = new Animal('foo');
9
a.walk();