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/

Panos K
  • 946
  • 6
  • 22

2 Answers2

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.

Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
  • 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? – Panos K May 03 '18 at 12:30
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

El Aoutar Hamza
  • 3,878
  • 2
  • 10
  • 19