Skip to content
Advertisement

How to create a prototype for this type of constructor?

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 …

function Animal(name){
  return { name };
}

And I wanna add a prototype property like walk(), but it doesn’t work here. I know it looks stupid, but…

Animal.prototype.walk = function () {
  console.log(`${this.name} is walking ...`);
}

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:

const animalProto = {
  walk() {
    console.log(`${this.name} is walking ...`);
  }
};
function Animal(name){
  return Object.assign(Object.create(animalProto), { name });
}
const a = new Animal('foo');
a.walk();

But this is strange, can you do it the normal way and assign to a property of this instead?

function Animal(name){
  this.name = name;
}
Animal.prototype.walk = function () {
  console.log(`${this.name} is walking ...`);
}

const a = new Animal('foo');
a.walk();

or if you want to avoid listing name twice

function Animal(name){
  Object.assign(this, { name });
}
Animal.prototype.walk = function () {
  console.log(`${this.name} is walking ...`);
}

const a = new Animal('foo');
a.walk();
Advertisement