gpt4 book ai didi

javascript - 这是如何在嵌套函数中工作的

转载 作者:行者123 更新时间:2023-11-30 16:41:47 25 4
gpt4 key购买 nike

我有以下代码片段。

var myObject = {
foo: "bar",

func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();

结果如下。

outer func:  this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar

我有几个关于这段代码的问题。

  1. 将嵌套函数放在外部函数中的想法是什么。这对现实生活中的代码有何好处?
  2. 我也在为“this”关键字苦苦挣扎,我一直认为“this”代表全局上下文,所以我对它在外部函数中的工作方式感到困惑,但在内部函数中却没有。

最佳答案

您的问题中确实有两个不同的概念:

  1. > this关键字。
  2. > closures .

尝试在闭包中使用 thisknown to confuse many people .

What is the idea of putting the nested function inside the outer function. How would that benefit real life code?

关于闭包有很好的文档。如果您不熟悉闭包,要点是它会记住定义函数的环境。

例如self.foo 确实返回了正确的值。

应用程序主要是函数式编程/currying。

例如闭包内的 self.foo 确实会返回正确的值,但您不必将该值传递给函数。

I'm also struggling with the 'this' keyword, I always thought 'this' represented the global context, so I'm confused with how it works in the outer function but not in the inner function.

在这个 block 内:

   (function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());

我们使用的不是对象方法,而是简单的调用。因为您没有使用 strict 模式,所以 this 默认为全局对象。

在这另一部分:

    console.log("outer func:  this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);

我们在一个对象方法中; this 引用对象 myObject

练习

  1. 如果在闭包内使用strict 模式会怎样?
  2. 如果您事先执行 window.foo = 'window foo'; 会发生什么情况?

关于javascript - 这是如何在嵌套函数中工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846695/

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