簡體   English   中英

Typescript獲得當前作用域或function()中的變量

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

我使用JQuery load功能append一些html數據append (而不是替換)到元素中。 我的問題是數據是this加載功能上的作用域。 不能使用() => 如何在加載回調之外訪問變量?

var element: JQuery;

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

在打字稿,當您使用() =>語法,它實際上只是創建一個變量包含了“這個電流意思”,然后替換的用法this調用生成的變量。 在需要this兩個含義的情況下,可以手動執行此操作。

這里有些例子...

在回調中正常使用this this是事件的目標。

$('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();

就像您期望的那樣。 您可以使用函數外的任何變量:

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