I define object a
with an empty method b()
. The method has no parameter and does nothing!
Please someone tell me, why when I call a.b()
and pass JS code as a parameter, does it execute the code?
var a = {
b() {}
}
a.b('' - alert(1) - '');
It works like a sink for example eval, setInterval, setTimeout and give JS code and execute it!
2
Answers
Maybe your misunderstanding is because of the syntax.
If you think about what you are passing to
a.b()
and only put this into the console, you will see:because you are doing some "mathematics" here: an empty string
''
minus the return of the funtion callalert(1)
(which returnsundefined
) and then minus another empty string.If you did the same with plus, javascript would concat everything into a single string:
So basically, your code is executed before anything is passed to the function
a.b
. If you don’t want this to happen, you would have to properly quote the call toalert(1)
in one of the following ways:It has therefore nothing to do with your function specifically.
Maybe it would be useful to you to think about the order in which the code is executed.
This code will do the same as yours but will help you see what happens.
Now, if you want the function to execute conditionally, following your will, you could try using a callback.