我想实现一个简单的上下文绑定,但它在 TypeScript 中不起作用。这是我的一段代码:
class Engine {
// some code...
spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
callbackfn.bind(new SpriteController(sprite), [this._ctx]);
}
// code again ...
}
Run Code Online (Sandbox Code Playgroud)
如果我想在另一个文件中使用 spriteController 方法,如下所示:
engine.spriteController(sprite, function(ctx) {
this.moveRight() // access to the spriteController class
})
Run Code Online (Sandbox Code Playgroud)
我希望能够在回调中使用 SpriteController 类。
在 JS 中,第一个参数(在 bind() 调用中)将“this”绑定到给定的对象。但是在 TypeScript 中,从 function.bind 创建的函数总是保留“this”。
如何在 TypeScript 中实现这一点?
我试图了解 PSR-7 是如何工作的,但我被卡住了!这是我的代码:
$app->get('/', function () {
$stream = new Stream('php://memory', 'rw');
$stream->write('Foo');
$response = (new Response())
->withHeader('Content-Type', 'text/html')
->withBody($stream);
});
Run Code Online (Sandbox Code Playgroud)
我的 Response 对象正在构建,但现在我想发送它... PSR-7 如何发送响应?我需要序列化吗?我可能错过了一件事......
那段代码发生了什么
var start = new Date();
setTimeout(function() {
var end = new Date();
console.log('Time elapsed with func1:',end - start, 'ms');
}, 500);
setTimeout(function() {
var end = new Date();
console.log('Time elapsed with func2:',end - start, 'ms');
}, 250);
while (new Date() - start < 1000) {}
Run Code Online (Sandbox Code Playgroud)
日志:
Time elapsed with func2: 1001 ms
Time elapsed with func1: 1017 ms
Run Code Online (Sandbox Code Playgroud)
我预计 func1 将首先被触发,因为它是要添加到事件队列中的第一个事件。然后,由于JS的单线程特性,等到func1返回后再执行队列中的下一个事件func2。
那么,发生了什么?