简体   繁体   English

在Javascript闭包中访问'this'

[英]Accessing 'this' in Javascript closure

This is more of a sanity check than anything else. 这比其他任何事情更像是一种健全性检查。 I've found that when working with closures in Javascript I often use the following pattern to access the enclosing class from within the function: 我发现在使用Javascript中的闭包时,我经常使用以下模式从函数中访问封闭类:

MyClass.prototype.delayed_foo = function() {
    var self = this;
    setTimeout(function() {
        self.foo(); // Be nice if I could use 'this' here
    }, 1000);
};

Obviously this works just fine, and it's not even a big hassle to work with. 显然这种方法很好,而且使用起来也不是很麻烦。 There's just this little itch in the back of my brain that says 'You're making this too complicated, dummy!' 在我的脑后只有这个小小的痒,说“你让这太复杂了,假的!” Is this the commonly accepted pattern? 这是普遍接受的模式吗?

这与异常的普遍接受的模式that经常使用的,而不是self

You can pull a sneaky using a binding function like this: 你可以使用像这样的绑定函数来偷偷摸摸地:

var Binder = function(fnc, obj) {
    return function() {
        fnc.apply(obj, arguments);
    };
};

and then changing your call to 然后将你的电话改为

MyClass.prototype.delayed_foo = function() {
    setTimeout(Binder(function(){
        this.foo("Lols");
    },this), 1000);
};

jsfiddle example: jsfiddle示例:

http://jsfiddle.net/ctrlfrk/6VaV6/ http://jsfiddle.net/ctrlfrk/6VaV6/

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

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