Difference between method definition and object's function property

前端 未结 1 1518
忘掉有多难
忘掉有多难 2021-01-23 07:01

This my code

const x = {
    a() {
      console.log(\"a\");
    },
    b: function() {
      console.log(\"b\");
    },

};

Is there a differe

1条回答
  •  时光说笑
    2021-01-23 07:11

    The only real difference is that a is defined as a method, meaning that it can't be instantiated with new:

    const x = {
      a() {
      },
      b: function() {
      }
    };
    
    new x.b();
    
    
    new x.a();

    A trivial difference is that, in sloppy mode, the method has the arguments and caller properties on its internal prototype, whereas the function has those properties on the function object itself:

    const x = {
      a() {
      },
      b: function() {
      }
    };
    
    console.log(x.a.hasOwnProperty('arguments'), x.a.hasOwnProperty('caller'));
    console.log(x.b.hasOwnProperty('arguments'), x.b.hasOwnProperty('caller'));

    Accessing these properties is forbidden in strict mode, and in method definitions. They are deprecated.

    0 讨论(0)
提交回复
热议问题