gpt4 book ai didi

javascript - "this"javascript 模块中的关键字

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

我已经全局定义了以下模块:

var module = (function () {

console.log(this);

this.fn = function () {
console.log(this);
}

return this;
})();

http://www.quirksmode.org/js/this.html :

在 JavaScript 中 |this|始终指代我们正在执行的函数的“所有者”,或者更确切地说,指代函数所属的对象。

第一次调用 console.logWindow 记录为 this 的值,我明白了。但是,第二次调用 console.log 也是如此。

既然this指的是函数的所有者,为什么module.fn记录Window而不是module?

当我调用fn时,我仍然必须编写module.fn,我不能编写Window.fn。由于 this 指的是 Window 我觉得这很令人困惑。

编辑:我忘记在我的示例中返回this

最佳答案

Since this refers to the owner of the function, why does module.fn log Window and not module?

外部函数的返回值是 window 因为它不会在任何特定上下文中被调用,所以 module 最终是 window > 也是如此。

看来您应用模块模式的方式是错误的。它应该返回在其余代码中使用的公共(public)接口(interface):

var module = (function () {
console.log(this);

// public interface
return {
fn: function () {
console.log(this);
}
}
})();

module.fn(); // "Object {fn: function}"

关于javascript - "this"javascript 模块中的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18460526/

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