繁体   English   中英

Function.prototype on 方法没有通过 object 的 this

[英]Function.prototype on method doesn't pass the this of the object

首先,对不起我的英语不好。

我想为 Function class 创建一个原型,例如:(延迟是一个例子)

import { delay } from 'lodash';

export default function(
    this: (...args: any) => any,
    wait: number,
    ...params: [any]
  ): any {
  return delay(this, wait, ...params);
};

我已经应用了它,当我从 function 调用它时,它运行良好:

console.log('render');
console.log.delay(1000, 'delayed render');

但是当我从一个方法调用它时,这没有通过:

class Test {
  constructor() {
    this.consoleLog('render');                      // Test {} render
    this.consoleLog.delay(1000, 'delayed render');  // undefined delayed render
  }
  consoleLog(text) {
    console.log(this, text);
  }
}

我怎样才能干净地传递“这个”?

我不认为问题出在您的延迟原型上,而是调用consoleLog方法下的console.log的上下文。

如果你这样定义它,你会看到你想要的上下文:

class Test {
  constructor() {
    this.consoleLog = this.consoleLog.bind(this);
    this.consoleLog('render');                      
    this.consoleLog.delay(1000, 'delayed render');
  }
  consoleLog(text) {
    console.log(this, text);
  }
}

我相信正在发生的事情是在consoleLog的上下文中调用delay ,并且由于delay最终调用this(params)没有上下文的任何内容(不通过 object 访问 - 即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"`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM