打字稿获取当前范围或函数内的变量()

时间:2013-06-03 09:28:40

标签: javascript typescript

我使用JQuery load函数将append(而不是替换)一些html数据添加到元素中。我的问题是数据是加载函数的this范围。无法使用() =>。如何访问负载回调之外的变量?

var element: JQuery;

$("<div></div>").load("http://www.google.de", function {
   $(element).append(this);
});

2 个答案:

答案 0 :(得分:5)

在TypeScript中,当您使用() =>语法时,它实际上只是创建一个变量来包含“this的当前含义”,然后用this的用法来代替调用生成的变量。您可以在需要this的两种含义的情况下手动执行此操作。

以下是一些例子......

在回调中正常使用thisthis是事件目标。

$('div').click( function () {
    // this is the clicked element
    alert('this: ' + this.id);
});

用于回调的TypeScript箭头函数。 this是词汇范围。

$('div').click( () => {
    // this is the lexical scope
    // i.e. the containing class, containing function, or window
    alert('this: ' + this.id);
});

手动示例,创建名为self的变量以包含词法范围并将this作为事件目标。

var self = this;
$('div').click( function () {
    // this is the clicked element
    alert('this: ' + this.id);

    // self is the lexical scope
    // i.e. the containing class, containing function, or window
    alert('self: ' + self.id);
});

值得注意的是,JavaScript在运行时遍历作用域链,因此如果未在函数内部定义变量,则JavaScript会检查变量的封闭函数。它一直走在链条上,直到它检查了全球范围。

此示例显示了此操作,但嵌套可以更深入并且仍然有效(即innerFunction内的函数仍然可以使用范围 - 步行来获取test变量。

var example = function () {
    var test = 'A test';

    var innerFunction = function () {
        alert(test); // 'A test'
    }

    innerFunction();
}

example();

答案 1 :(得分:1)

正如您所料。函数外的任何变量都可供您使用:

var element: JQuery;
var someOther = "123";

$("<div></div>").load("http://www.google.de", function(){
   $(element).append(this);
   $(this).text(someOther);
});