Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a function is called using call/apply

Tags:

javascript

function foo(){
    console.log('foo', this);
}

foo();
foo.call({ bar: 1 });
foo.apply([{ bar: 1 }]);

Is there any way to know if foo() was called using a normal invoke or call/apply?

http://jsfiddle.net/H4Awm/1/

like image 734
Johan Avatar asked Oct 29 '13 12:10

Johan


People also ask

What does it mean to call a function from an object?

This means that we can call any function and explicitly specify what this should reference in the calling function. It returns the result of the function which is invoked by this. The apply method is used for allowing a function/object belonging to an object x to be called and assigned to an object y.

What is the use of the call() method in JavaScript?

The call () method is used to call a function with a given this and arguments provided to it individually. This means that we can call any function, explicitly specifying the reference that this should reference in the calling function.

How do I test if a mock function has been called?

Next, we call jest.spyOn on the component method that we expect to call if we click the button. We call forceUpdate to update our component that we want to test with the spy. Then we find the p element with the class button . Then we call simulate ('click') on that to click it. And then we check if the mock function has been called.

How to check if a function is called in Unity?

- Unity Answers How to check if a function is called? Is there a way to check if a function is called? Have the function return a bool, or have the function change a bool. Debug.Log("In Sample Function!"); Anywhere in the function you're trying to call.


1 Answers

No. You can't detect if a function is called from call/apply or normally.

They're not magical beings, all they do is set the arguments and this value. There is a subtle difference when it comes to undefined/undeclared values but that's it.

All .apply and .call do in ES5 is:

Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.

It sets the internal caller attribute correctly so something naive like this would not work.

like image 134
Benjamin Gruenbaum Avatar answered Oct 10 '22 00:10

Benjamin Gruenbaum