Difference between method definition and object

2020-04-17 07:05发布

This my code

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

};

Is there a difference between a & b functions?

I read somewhere, that the a() {} way of creating methods is shorter, but can bring a number of problems.

Use it only in those cases when you are sure that you will never use recursion or pass a function to events handlers.

Is this true?

标签: javascript
1条回答
够拽才男人
2楼-- · 2020-04-17 08:04

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.

查看更多
登录 后发表回答