gpt4 book ai didi

javascript - typescript 获得函数内的当前范围或变量()

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:35 25 4
gpt4 key购买 nike

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

var element: JQuery;

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

最佳答案

在 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();

关于javascript - typescript 获得函数内的当前范围或变量(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16893660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com