作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试了解如何最好地使用 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();
test1
和 test2
都打印了对 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/
我是一名优秀的程序员,十分优秀!