“这个”闭包中的关键字 [英] "this" keyword inside closure

查看:128
本文介绍了“这个”闭包中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请看下面的代码:

  var test =(function(){
var t =test;
return {
alertT:function (){
alert(t);
}
}
}());

我在window.load上有一个函数,如:

  test.alertT(); 

这一切都很好。但是,当我尝试在 alert()中在 alertT 中显式设置 t 的上下文时,

我试过:

  var that = this; 
alert(that.t); // undefined

我试过:

  return {
:this,
alertT:function(){
alert(that.t); // undefined!
}
}

我试过:

  var test =(function(){
var t =test;
var myObj = this;
return {
alertT:function(){
alert(myObj.t); // undefined!
}
}
}

我缺少什么?我需要能够明确地为回调等事情设置上下文。我也看到了例子(http://stackoverflow.com/questions/346015/javascript-closures-and-this-context),看起来像什么

解决方案

t 只是外部匿名函数范围内的正常变量(因此也是内部匿名函数)。它不是一个对象上的属性,所以你只需设置它不需要引用 this code> the_other 。

  var test =(function(){
var t =test;
return {
alertT:function(){
alert(t);
},
setT:function(new_value){
t = new_value;
}
}
}());
test.alertT();
test.setT('hello,world');
test.alertT();

您使用的语法是创建在JS中作为私有变量的东西的通常模式。


I've seen a bunch of examples but can't seem to get some sample code to work.

Take the following code:

var test = (function(){
    var t = "test";
    return {
        alertT: function(){ 
            alert(t);
        }
    }
}());

and I have a function on window.load like:

test.alertT();

That all works fine. However, when I try to explicitly set the context of t inside the alert() in alertT, I just get undefined.

I've tried:

var that = this;
alert(that.t); //undefined

I've tried:

        return {
            that: this,
            alertT: function(){ 
                alert(that.t); // undefined!
            }
        }

and I've tried:

var test = (function(){
    var t = "test";
    var myObj = this;
    return {
        alertT: function(){ 
            alert(myObj.t); // undefined!
        }
    }
}());

what am I missing? I need to be able to set the context explicitly for things like callbacks etc. I've seen examples too (http://stackoverflow.com/questions/346015/javascript-closures-and-this-context) that seem like what I'm doing, so why does this not work?

解决方案

t is just a normal variable in the scope of the outside anonymous function (and thus also the inner anonymous function). It isn't a property on an object, so you simply set it without reference to this, that, or the_other.

var test = (function(){
    var t = "test";
    return {
        alertT: function(){ 
            alert(t);
        },
        setT: function (new_value) {
            t = new_value;
        }
    }
}());
test.alertT();
test.setT('hello, world');
test.alertT();

The syntax you are using is the usual pattern for creating something that acts like a private variable in JS.

这篇关于“这个”闭包中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆