skip to Main Content

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


  1. 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:

    > ''-alert(1)-''
    NaN
    

    because you are doing some "mathematics" here: an empty string '' minus the return of the funtion call alert(1) (which returns undefined) and then minus another empty string.

    If you did the same with plus, javascript would concat everything into a single string:

    > ''+alert(1)+''
    "undefined"
    

    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 to alert(1) in one of the following ways:

    'alert(1)'
    "alert(1)" // but not ''alert(1)''
    `alert(1)`
    

    It has therefore nothing to do with your function specifically.

    Login or Signup to reply.
  2. Maybe it would be useful to you to think about the order in which the code is executed.

    1. In this case, even if you don’t require any parameter in your a object’s method, due to the javascript flexibility at first it won’t throw any error.
    2. Besides, if you pass to the method the result of the execution of another as an argument, it will run it and get the result even if you neither use it nor require it.
      This code will do the same as yours but will help you see what happens.
    const a = {
       b(hiddenArgument){
           // Doesn't do anything with the argument. If not passed will be undefined.
       }
    };
    const process = alert(1); // This will be executed as long as you invoke it in this line and will return undefined.
    a.b('' - process - '');
    

    Now, if you want the function to execute conditionally, following your will, you could try using a callback.

    const a = {
       b(callback){
           if(some_condition){
              let data = callback();
              // Here you can do something with your data.
           }
       }
    };
    const process = () => '' - alert(1) - ''; // This will be executed as long as you invoke it inside the function.
    a.b(process);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search