0

Hello guys runned into this issue

can someone explains me how this works?

function anyOther(){ return "otherFunction"; } function getLocation() { return window.location.toString(); } function myFunc(data, func) { console.log(data, func()); } myFunc("From", getLocation); myFunc("From", anyOther); myFunc("From", window.location.toString); 

why passing window.location.toString() inline does not work and passing it after we wrap it in a function works

https://jsfiddle.net/w9jhdzm7/

3
  • what is console.log(data,func()) there is no func function in your code., see your browser's console. Commented May 3, 2018 at 12:25
  • @yash func is give as argument to myFunc Commented May 3, 2018 at 12:25
  • 1
    Try myFunc("From", window.location.toString.bind(window.location)); Commented May 3, 2018 at 12:28

2 Answers 2

1

In the third myfunc call you are passing a function of the window object.

function anyOther(){ return "otherFunction"; } function getLocation() { return window.location.toString(); } function myFunc(data, func) { console.log(data, func()); } myFunc("From", getLocation); myFunc("From", anyOther); 

This is not working because this function will only work in the context of the window object. Now you are calling it not in the context of the window object.

myFunc("From", window.location.toString); 

This is because you are passing a reference of the function to the myFunc function which then tries to call this function. Because this is not in the context of the window object this will fail.

When not to pass functions as reference:

When the functions are native implementations of the browser you can't pass the functions as arguments in another function. You can see if it is a implementation of the browser if you can see native code like this:

enter image description here

window.Object.assign is a function which is implemented by the browsers and thus we cannot pass this as function argument and expect it to work.

Sign up to request clarification or add additional context in comments.

1 Comment

nice explanation so this only has to do with the fact that im calling a function of window there is any other case which i should take care of?
1

Because when you do this :

myFunc("From", window.location.toString); 

Inside myFunc, the function is called on the global object, not on window.location

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.