Calling a function without parentheses returns whole function as a string

前端 未结 6 1128
一生所求
一生所求 2021-01-19 01:10

I created a JavaScript object like this:

var obj = {
  a: 10,
  b: 20,
  add: function(){
     return this.a + this.b;
  }
};

I executed the

6条回答
  •  滥情空心
    2021-01-19 01:54

    Without parentheses, you're retrieving a reference to the function, you are not calling (executing) the function

    With parentheses, you're executing the function.

    function a() {
      return 2;
    }
    
    var b = a(); // called a, b is now 2;
    var c = a; // c is referencing the same function as a
    console.log(c); // console will display the text of the function in some browsers
    var d = c(); // But it is indeed a function, you can call c(), d is now 2;

提交回复
热议问题