1

If I have the following object literal, I understand that val and prop are properties of the obj object.

const obj = {
  val: 7,

  prop: function() {
    alert("prop " + this.val);
  },

  met() {
    alert("met " + this.val);
  }
};

obj.prop();
obj.met();

Property prop holds a reference to an anonymous function. Such a property is also referred to as a method.

In Visual Studio IntelliSense:

  • prop is referred to as property,
  • met is referred to as method.

But

  1. What is met?
  2. How does it differ from prop?
  3. When to use prop syntax and when met?
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
tibx
  • 840
  • 13
  • 20
  • 1
    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions – danh Jan 26 '23 at 18:34
  • Actually, that doc says, mysteriously... "However, note that the method syntax is not equivalent to a normal property with a function as its value — there are semantic differences". I think that last phrase is at the heart of your question. – danh Jan 26 '23 at 18:37
  • 1
    Methods are non-constructable, i.e. they cannot be used with `new`. Other than that, it comes down to preference. Your `function` is also not anonymous; see [How does an anonymous function know its name?](/q/73804138/4642212). – Sebastian Simon Jan 26 '23 at 18:37
  • 2
    @SebastianSimon I wouldn't say it's up to preference. Unless you *need* a `function`, method definition syntax is cleaner, more straightforward, slightly more efficient (doesn't allocate a prototype object) and should be preferred. – Bergi Jan 26 '23 at 18:40

0 Answers0