[英]Inject variable into callback function scope
Is this possible to add variable to callback scope? 这是否可以将变量添加到回调范围? What I want to achieve is:
我想要实现的是:
... Foo.prototype.bar = function(fn) { var baz = "baz!"; fn.call(this); } ...
Foo.bar(function() { console.log(baz) // gives "baz!" });
I know I can pass baz
variable as an argument or this
but I'm interested in something like above. 我知道我可以传递
baz
变量作为参数或者this
但我对上面的内容感兴趣。
No, it's not possible. 不,这是不可能的。 The only ways are the ones you pointed out: as an argument or in
this
. 唯一的方法是你指出的:作为论据或在
this
。
What about doing it this way: 怎么样这样做:
var Foo = function(){}
Foo.prototype.handle = function(fn) {
var baz = "baz !";
eval('(' + fn.toString() + ')();');
}
var foo = new Foo;
foo.handle(function (){
console.log(baz);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.