简体   繁体   English

Typescript获得当前作用域或function()中的变量

[英]Typescript gain current scope or variable inside function()

i use the JQuery load function to append (instead of replace) some html data to an element. 我使用JQuery load功能append一些html数据append (而不是替换)到元素中。 My problem is the data is the this scope on the load function. 我的问题是数据是this加载功能上的作用域。 Can not use () => . 不能使用() => How can i access a variable outside of the load callback ? 如何在加载回调之外访问变量?

var element: JQuery;

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

In TypeScript, when you use the () => syntax, it actually just creates a variable to contain the "current meaning of this" and then substitutes usages of this to call the generated variable. 在打字稿,当您使用() =>语法,它实际上只是创建一个变量包含了“这个电流意思”,然后替换的用法this调用生成的变量。 You can do this manually in situations where you want both meanings of this . 在需要this两个含义的情况下,可以手动执行此操作。

Here are some examples... 这里有些例子...

Normal use of this in a callback. 在回调中正常使用this this is the event target. this是事件的目标。

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

TypeScript arrow function used for a callback. 用于回调的TypeScript箭头函数。 this is the lexical scope. this是词汇范围。

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

Manual example, creating a variable named self to contain the lexical scope and leaving this to be the event target. 手册例如,创建一个名为变量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);
});

It is worth bearing in mind that JavaScript walks the scope chain at runtime, so if a variable isn't defined inside of a function, JavaScript inspects the enclosing function for the variable. 值得注意的是,JavaScript在运行时会遍历作用域链,因此,如果未在函数内部定义变量,则JavaScript会检查该变量的封闭函数。 It keeps walking up the chain until it has checked the global scope. 在检查全局范围之前,它一直沿链条前进。

This example shows this in action, but the nesting can be much deeper and it still works (ie a function inside of innerFunction can still scope-walk to get to the test variable. 此示例实际显示了这一点,但是嵌套可以更深入,并且仍然有效(即, innerFunction内部的函数仍可以作用域移动以到达test变量。

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

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

    innerFunction();
}

example();

Just as you would expect. 就像您期望的那样。 Any variable outside the function is available to you: 您可以使用函数外的任何变量:

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

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

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

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