如何为这种类型的构造函数创建原型?

How to create a prototype for this type of constructor?

我探索了 JavaScript 的深处。

好吧,假设我有一个这样的构造函数。是的,我知道这是一种创建构造函数的奇怪方式,但是 ...

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

我想添加一个原型 属性,例如 walk(),但它在这里不起作用。我知道这看起来很愚蠢,但是...

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

问题:有什么方法可以将此步行 属性 添加为原型 属性?

如果您必须在构造函数中显式 return 一个不是 this 的对象,则:

在外面创建原型对象,然后在构造函数里面使用Object.create

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();

但这很奇怪,你能不能用正常的方式来做,然后分配给 this 的 属性?

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

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

或者如果您想避免列出 name 两次

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

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