[英]Function.prototype on method doesn't pass the this of the object
First of all, sorry for my bad english.首先,对不起我的英语不好。
I want to create a prototype for Function class like: ( delay is an example )我想为 Function class 创建一个原型,例如:(延迟是一个例子)
import { delay } from 'lodash';
export default function(
this: (...args: any) => any,
wait: number,
...params: [any]
): any {
return delay(this, wait, ...params);
};
I've applied it and when I call it from a function it's work well:我已经应用了它,当我从 function 调用它时,它运行良好:
console.log('render');
console.log.delay(1000, 'delayed render');
but when I call it from a method the this isn't pass:但是当我从一个方法调用它时,这没有通过:
class Test {
constructor() {
this.consoleLog('render'); // Test {} render
this.consoleLog.delay(1000, 'delayed render'); // undefined delayed render
}
consoleLog(text) {
console.log(this, text);
}
}
How can I pass the 'this' cleanly?我怎样才能干净地传递“这个”?
I don't believe the problem is your delay prototype, it's the context in which the console.log
under the consoleLog
method is being invoked.我不认为问题出在您的延迟原型上,而是调用
consoleLog
方法下的console.log
的上下文。
If you define it like this, you'll see the context you want:如果你这样定义它,你会看到你想要的上下文:
class Test {
constructor() {
this.consoleLog = this.consoleLog.bind(this);
this.consoleLog('render');
this.consoleLog.delay(1000, 'delayed render');
}
consoleLog(text) {
console.log(this, text);
}
}
I believe what's happening is that delay
is being called on the context of consoleLog
, and since delay
is ultimately calling whatever this(params)
is with no context (not being accessed via an object -- ie consoleLog('delayed render')
instead of someObj.consoleLog('delayed render')
), thus undefined
.我相信正在发生的事情是在
consoleLog
的上下文中调用delay
,并且由于delay
最终调用this(params)
没有上下文的任何内容(不通过 object 访问 - 即consoleLog('delayed render')
而不是someObj.consoleLog('delayed render')
),因此undefined
。 I hope that makes sense.我希望这是有道理的。
To paint it using a pseudo stacktrace:使用伪堆栈跟踪绘制它:
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"`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.