gpt4 book ai didi

javascript - 将 javascript 对象作为函数调用

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

Jest testing framework ,有一个 jest.genMockFn() 函数创建可以作为函数调用并同时访问其属性的对象。

var mockFn = jest.genMockFn()
mockFn('Hello world!')
mockFn('The world is yours.')
console.log(mockFn.mock.calls) // [["Hello world!"], ["The world is yours."]]

当我转储mockFn时,我得到:

{ [Function]
_isMockFunction: true,
mock:
{ calls: [ [Object], [Object] ],
instances: [ [Object], [Object] ] },
mockClear: [Function],
mockReturnValueOnce: [Function],
mockReturnValue: [Function],
mockImpl: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
_getMockImplementation: [Function] }

我不明白他们是如何实现这一目标的。有任何想法吗?能提供类似功能的代码吗?谢谢。

最佳答案

函数的定义是

4.3.24 function

member of the Object type that is an instance of the standard built-in Function constructor and that may be invoked as a subroutine

所以拥有一个可以被调用的对象并不奇怪。所有函数的行为都是如此。

具体来说,这是使用 [[Call]] 完成的,一个 internal property仅为某些对象定义。

Executes code associated with the object. Invoked via a function call expression. [...] Objects that implement this internal method are callable.

关于javascript - 将 javascript 对象作为函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016668/

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