在 Scala 中,具有两个参数的函数的类型为:
class Function2[InputTypeParameter1,InputTypeParameter2, OutputTypeParameter] {
def apply(x:InputTypeParameter1,y:InputTypeParameter2 ):OutputTypeParameter=f(x,y);
}
Function###
类有一个方法,apply
。当方法用作函数对象时,它会更改为具有 apply
方法的函数对象。
方法不能是 Function###
对象,因为如果是的话,它们将有一个 apply
方法,该方法将是 Function###
对象将有一个方法apply
,该方法将...
JavaScript 是否以类似的方式工作?
最佳答案
什么是 javascript 中的函数
MDN 很好地描述了函数:
In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around just like any other object. Specifically, they are Function objects.
函数由 Function.prototype 组成(其根是 Object.prototype )。
JavaScript 中的函数是如何解释的
Function.prototype
包含一个方法 Function.prototype.call()
calls (executes) a function and sets its this to the provided value, arguments can be passed as they are.
您可能见过显式使用 call()
来传递 this
的代码,如下所示:
function speak(phrase) {
document.write(phrase + ' ' + this.name);
}
function foo() {
this.name = "Foo";
}
speak.call(foo, "Hello");
好吧,Javascript 在内部使用 Function.prototype.call()
方法来调用所有函数/方法。所以
function speak(phrase) {
document.write(phrase);
}
speak("Hello");
实际上解释为:
function speak(phrase) {
document.write(phrase);
}
speak.call(window, "Hello");
当使用严格模式时,根据 ECMAScript 5,有细微的变化:
speak.call(undefined, "Hello");
请注意,它没有将 window
作为 this
参数传递,而是传递了 undefined
。
最后,当使用函数作为对象的一种“方法”时:
var speaker = {
speak: function(phrase) {
document.write(phrase);
}
}
speaker.speak("Hello");
变成
var speaker = {
speak: function(phrase) {
document.write(phrase);
}
}
speaker.speak.call(speaker, "Hello");
JavaScript 函数与 Scala 函数/方法的比较
虽然我不了解 Scala,但我确实查阅了一些有关 apply
方法的信息,它听起来有点类似于 call()
。还根据这个其他SO answer
Under the hood, there are other differences between functions and methods. Generally, a plain method generated less overhead than a function (which technically is an object with an apply method).
因此,我想说 javascript 函数与 Scala 函数对象非常相似。但 javascript 中的方法实际上只是函数,而函数实际上只是对象,因此 javascript 方法与 Scala 方法不同。希望这能回答您的问题。
更新:javascript 的 call()
方法如何工作
call()
是一个抽象操作,它使用函数对象的内部方法[[call]]
。内部的 [[call]]
方法带我们深入了解 javascript 代码执行的本质。我只简单介绍一下所发生的事情:
- JavaScript 内部操作,PrepareForOrdinaryCall ,是为了处理更多与上下文相关的事情而执行的。
- 另一个内部操作,OrdinaryCallBindThis发生...这设置了一些更多与上下文相关的内容以及在执行期间使用的函数的
this
。 - 第三个内部操作,OrdinaryCallEvaluateBody ,执行。这是函数体实际被解析、解释和执行的地方。
如果你想真正深入了解这一点,我刚才所说的所有内容都可以在 EMCAScript Language Specification 中找到。 .
关于javascript - JavaScript 函数对象与 Scala 函数对象有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599175/