Я не верю, что проблема заключается в вашем прототипе задержки, это контекст, в котором вызывается console.log
в методе consoleLog
.
Если вы определите его таким образом, вы посмотрите контекст, который вы хотите:
class Test {
constructor() {
this.consoleLog = this.consoleLog.bind(this);
this.consoleLog('render');
this.consoleLog.delay(1000, 'delayed render');
}
consoleLog(text) {
console.log(this, text);
}
}
Я верю, что происходит то, что delay
вызывается в контексте consoleLog
, а поскольку delay
в конечном счете вызывает то, что this(params)
не имеет контекст (недоступный через объект - то есть consoleLog('delayed render')
вместо someObj.consoleLog('delayed render')
), таким образом undefined
. Я надеюсь, что это имеет смысл.
Чтобы нарисовать его с помощью псевдо стека трассировки:
Normal execution context:
const test = new Test()
test.consoleLog('abc')
-> consoleLog gets called in the context of `test`
-> console.log thus displays `Test` as the object `this` is referring to
Delayed execution context:
const test = new Test()
-> delay gets called with consoleLog as `this`
-> this(params) gets executed (consolLog(params))
-> since consoleLog was not called ON an object (see test.consoleLog above)
its context is undefined in strict mode, thus `console.log(this, text)` will
show `undefined "delayed render"`