gpt4 book ai didi

javascript - 如何从 JavaScript 模块中访问 "this"?

转载 作者:行者123 更新时间:2023-11-29 18:25:12 25 4
gpt4 key购买 nike

我正在尝试了解如何最好地使用 JavaScript 模块模式。我的问题是似乎没有办法从自身内部引用模块,因为 this 被设置为 Window 对象。

我有这个简单的测试代码:

var Test = function() {
var that = this;

return {
something: function() {
console.info(that);
}
}
}

var test1 = Test();
test1.something();

var test2 = Test();
test2.something();

test1test2 都打印了对 Window 对象的引用,而不是模块本身。

知道如何更改它以便我在模块中有一个有效的 this 吗?

最佳答案

如果你这样做了

var test1 = new Test()

然后你可以做

test1.something(); 

另一种模块结构是做这样的事情:

var myModule = function () {
var obj = {};
obj.something = function () {
return console.log(obj);
};
obj.something2 = function () {
return console.log(obj === this); // true
};
return obj;
};
var test = myModule();
test.something();
test.something2();

希望对你有帮助

关于javascript - 如何从 JavaScript 模块中访问 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14212466/

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