如何解决这个嵌套函数中的“this”关键字有什么意义
此函数在 JavaScript 中计算 f(g(...arg))
。
function compose(f,g){
return function(...arg){
return f.call(this,g.apply(this,args)};
}
}
我知道方法 call
和 apply
的第一个参数是调用上下文。但是,我不确定 this
关键字在上述 call
和 apply
方法中的意义是什么。当调用上下文是像{x:1}
这样的对象时,我更清楚,然后我们可以使用this.x
来访问属性x
,但我不清楚{{的使用1}} 在上述上下文中。为什么我们在上面的代码中这样使用 this
?
this
解决方法
这是因为我们要保留 this
的原始调用值并将其转发给所有组合函数。
如果我们将不使用 this
的函数组合在一起,这并不重要,就像您的示例一样:
const sum = (x,y) => x + y;
const square = x => x * x;
compose(square,sum)(2,3);
这里,this
无关紧要。
然而,组合是通用的,应该适用于任何一对函数。我们可以使用this
,在这种情况下,最好保留它们的工作方式,以防万一:
function compose(f,g){
return function(...args){
return f.call(this,g.apply(this,args));
}
}
function introduce(greeting) {
return `${greeting}! My name is ${this.name}.`;
}
function addRandomFact(str) {
return `${str} I like ${this.hobby}.`;
}
const person1 = {
name: "Alice",hobby: "pancakes",introduce: introduce,}
console.log(person1.introduce("Hello"));
const person2 = {
name: "Bob",hobby: "turtles",introduce: compose(addRandomFact,introduce)
}
console.log(person2.introduce("Hola"));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。