我见过很多例子,但似乎无法获得一些示例代码。
请使用以下代码:
var test = (function(){
var t = "test";
return {
alertT: function(){
alert(t);
}
}
}());
我在window.load上有一个函数,如:
test.alertT();
一切正常。但是,当我尝试在 alertT 中的 alert()中显式设置 t 的上下文时,我只是未定义。
我试过了:
var that = this;
alert(that.t); //undefined
我试过了:
return {
that: 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),看起来像我我在做什么,为什么这不起作用?
答案 0 :(得分:1)
t不在'this'的范围内。 t是该方法的局部变量。所以你需要做的地方
this.t = whatever
...
这是我正在编写的应用程序的真实例子
var scope = this;
cells.forEach(function(cell, index) {
var given = cell.get('given');
var value = cell.get('value'),
valueAsString = '%@'.fmt(value);
var rowValues = scope.getRowForIndex(index);
...
}
forEach函数内的范围是我迭代的数组'cells'的范围。因为我想在调用范围内做事,所以我使用了一个闭包......
答案 1 :(得分:1)
t
只是外部匿名函数范围内的正常变量(因此也是内部匿名函数)。它不是对象的属性,因此您只需设置它而不引用this
,that
或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中创建类似私有变量的通常模式。
答案 2 :(得分:0)
在C#和Java中,可以这样做:
public class MyClass {
private int x;
public void DoSomething(int x) {
int a = this.x;
int b = x;
}
}
变量a和b将具有来自不同x的值,因为一个是类的x,一个是方法x。
现在,想象一下,如果你不能使用this
明确引用类的x。然后你必须做以下事情:
public class MyClass {
private int classX;
public void DoSomething(int x) {
int a = classX;
int b = x;
}
}
我在JavaScript中的情况非常多。至少在你描述的情况下。通过使用方法apply
和call
,您可以更改执行函数的上下文,但是您永远不能区分具有相同名称但不同范围的变量。你只需要使用不同的名称。