最近,我被一堆JavaScript谜语迷住了,我真的被这个谜语困扰了一天半(根据上下文,所有其他的谜语都最多花了1个小时).因为我想自己想出最终的解决方案,所以我将发布一个有点类似的代码段,这样我就可以抓住大意并根据谜语的上下文实现它.
假设这是一段代码:
class Vehicle {
constructor(brand, model, power) {
this.brand = brand;
this.model = model;
this.power = power;
}
info() {
return `This vehicle is a ${this.brand} - ${this.model}, with a power of ${this.power}`;
}
}
//do something with my class here such that
//the next calls will return/display as follows
const v = new Vehicle('Mercedes', 'C class', 12345);
console.log(v.info()); // This vehicle is a Mercedes - C class, with a power of 12345
const {
info
} = v;
console.log(info()); // This vehicle is a Mercedes - C class, with a power of 12345
//To keep in mind, the function should stay the same, so a call to (info === v.info) should return true;
//And only the part of the code where it says to enter the code can be changed, so the class should be untouched.
我知道这不应该是一个可能会在日常生活中使用的情况,因为它是一个谜,只是为了挑战我们的大脑,但它挑战了我,以至于我放弃了哈哈.
我try 循环遍历Vehicle.Prototype的条目,并设置每个是函数的条目,而不是绑定到类、.Prototype或任何类似内容的相同函数的构造函数,但都不起作用.
我如何着手解决它,或者至少让它让我可以在每次创建该类的新实例时编辑函数调用?
编辑: 我try 使用绑定方法,甚至try 了如下所示
Vehicle.prototype['info'] = Vehicle.prototype['info'].bind(Vehicle.prototype);
Vehicle.prototype['info'] = Vehicle.prototype['info'].bind(Vehicle);
Vehicle.prototype['info'] = Vehicle.prototype['info'].bind(Vehicle.prototype['info']);
我try 了许多替代方案,但它们都不起作用,因为我必须将其绑定到创建的类的每个实例上.因此,如果创建了一个新实例,并且在那里执行了相同的操作,则每个实例都将根据从中提取数据的实例返回数据.