gpt4 book ai didi

javascript - 在 JavaScript 中使用装饰器时箭头函数和函数的区别

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

我是 JavaScript 的新手,目前正在研究动态作用域的工作原理。现在我明白了 this 是如何获得它的值(value)的。我已经阅读了所有规则并理解了其中的大部分规则,但是我无法理解这段代码,它解释了在装饰器中使用箭头函数和函数之间的区别。这是代码的链接 https://javascript.info/arrow-functions .

箭头函数代码

function defer(f, ms) {
return function() {
//What is this? Why use apply?
setTimeout(() => f.apply(this, arguments), ms)
};
}

function sayHi(who) {
alert('Hello, ' + who);
}

let sayHiDeferred = defer(sayHi, 2000);
sayHiDeferred("John"); // Hello, John after 2 seconds

并且具有正常的功能

function defer(f, ms) {
return function(...args) {
// What's the purpose of this line?
let ctx = this;
setTimeout(function() {
// Again why apply?
return f.apply(ctx, args);
}, ms);
};
}

这是我难以理解的内容。

  1. 为什么我们甚至在这两种情况下都使用 apply?我们不能不申请吗?
  2. 如果我简单地调用 f 而不是使用 f.apply 会发生什么?
  3. 我们使用 apply 是因为 setTimeOut 吗?

如有任何解释,我们将不胜感激。

最佳答案

可靠的问题 - 老实说 - 这是您正在思考的好兆头。

Why are we even using apply in both cases? Can't we do it without apply?

值得了解.apply (及其兄弟 .bind )来 self 们没有自动绑定(bind)“this”上下文的箭头函数的时代。所以,只要知道 - 它们来自更早的时代。

现在,它们的用途是什么(申请/绑定(bind))?当你想分配“这个”时,你真的只需要它们。在您提供的案例中,您没有引用 this - 这意味着如果您只是正常调用这些函数,您将获得相同的结果。这也解决了您的问题:

What would happen if I simply call f instead of using f.apply?

没有。你会得到相同的结果。

Are we using apply because of setTimeOut?

看起来您正在使用您在 Internet 上看到的一些示例 - 但简短的回答是:是的,您会使用 . .apply.bind什么时候因为 setTimeOut。但是您提供的示例隐藏了实际的类(class)。

这是一个尝试。


function iReferenceThisForStuff() {
console.log(this.foo)
}

setTimeout(iReferenceThisForStuff, 10)

// ...10ms pass

// "undefined" is logged because "this" references the global window object

在上面的示例中,我们将一个非绑定(bind)函数传递给了超时,并记录了window.foo。因为 - 当未明确设置时 - this是对全局范围的引用。这是一种回退行为,非常奇怪 - 但它就是这样工作的。

使用 .bind.apply示例:


function iReferenceThisForStuff() {
console.log(this.foo)
}

setTimeout(iReferenceThisForStuff.bind({ foo: "bar" }), 10)

// ...10ms pass

// "bar" is logged because "this" references the object reference passed to `.bind`

// You could have also done...

setTimeout(function () {
return iReferenceThisForStuff.apply({ foo: "bar" }, /* maybe some additional args */)
}, 10)

// and you would have the same outcome.

关于箭头函数的最后说明。他们绑定(bind) this不管怎样this在实例化它们的闭包中。

(function () {
setTimeOut(() => { // This arrow function is instantiated in a closure where `this` is a reference to { foo: "bar" } and is automatically bound.
console.log(this.foo) // Will eventually log "bar"
})
}.bind({ foo: "bar" }))

关于javascript - 在 JavaScript 中使用装饰器时箭头函数和函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56532889/

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