我正在尝试解决一些有关原型(可能还有闭包)的JavaScript问题。我非常是这个概念的新手。
我需要创建一个MyNumber原型,然后添加增量函数,该函数将返回一个递增1的数字。在这里,我将创建该原型的多个实例,每个实例将分别跟踪其自身的值。
这是我逻辑上破碎的代码:
function MyNumber(num) {
this.num = num;
}
MyNumber.prototype.increment = function() {
return function() {
++this.num
}
}
在此示例之后,我需要创建一个Clock原型,该原型将每秒增加一个。
虽然您正在使用函数构造函数,但我建议您使用ES6的classes。它使您可以编写更具可读性和可维护性的代码。通过创建自己的MyNumber
和class
方法,可以将constructor()
函数设置为increment()
。 increment()
方法负责递增编号并返回新编号。
由于需要时钟,所以您还可以添加一个额外的Clock
类。此extends
是MyNumber
类,它允许Clock
访问在MyNumber
类中声明的属性和方法。由于时钟需要有一个内部计数器,因此我们可以扩展MyNumber
,为我们提供此计数功能。
Clock
类具有一个构造函数,该构造函数通过执行MyNumber
调用来调用super()
的构造函数。这将初始化this.num
类中的Clock
。构造函数还接受其他参数,例如动作,该函数每次在时钟“滴答”一声时都会执行一个函数,并为时钟“滴答”多长时间提供speed
。
Clock
类还实现了begin()
方法,该方法使用setInterval()
重复执行传递的箭头功能。箭头函数每x m / s执行一次(基于this.speed
属性)。每次执行箭头功能时,它都会使时钟内部计数器递增(使用扩展的.increment()
类提供的MyNumber
)。它还执行最初通过构造函数传递的action
函数。
然后您可以创建Clock
类的实例,并将所需的参数传递给构造函数,如下所示:
class MyNumber {
constructor(num) {
this.num = num;
}
increment() {
return ++this.num;
}
}
class Clock extends MyNumber {
constructor(beginTime, action, speed=1) { // default speed to `1`
super(beginTime);
this.act = action;
this.speed = speed; // in seconds
}
begin() {
this.act(this.num); // call once before looping
setInterval(() => { // executes every `this.speed` seconds
const new_time = this.increment(); // increment the time and get the new time
this.act(new_time); // execute the action
}, this.speed*1000);
}
}
const clock = new Clock(3, t => console.log(`Tick tock, the time is ${t}`));
clock.begin();
我在这里看到的主要问题是,它返回的increment
而不是简单地增加this.num
的方法,而是增加了function
的方法。在下面的示例中,我将其重写为简单地自己进行增量。同样在示例中,我们确保使用this.num
创建新实例,以便JS引擎知道我们正在创建对象的新实例: