admin管理员组文章数量:1026125
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.
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.
-
You probably mean
(new Foo).bar
, since it's a property of instances, not of the constructor. – pimvdb Commented Dec 24, 2011 at 22:50
2 Answers
Reset to default 4No, it's not possible. The only ways are the ones you pointed out: as an argument or in 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);
});
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.
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.
-
You probably mean
(new Foo).bar
, since it's a property of instances, not of the constructor. – pimvdb Commented Dec 24, 2011 at 22:50
2 Answers
Reset to default 4No, it's not possible. The only ways are the ones you pointed out: as an argument or in 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);
});
本文标签: javascriptInject variable into callback function scopeStack Overflow
版权声明:本文标题:javascript - Inject variable into callback function scope - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745635717a2160435.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论