Why does a method using the shorthand method synta

2019-05-28 16:20发布

问题:

In the code snippet below func2 is supposed to be the shorthand method syntax for func1.

Question 1: Why does obj1 contain the prototype Object and obj2 does not (while both have the __proto__ object)?

Question 2: Are all three objects prototype objects?

Question 3: Why does the fact of obj2 not having a prototype function not influence the way in which it binds this?

Concerning obj3: obj3 is there for reference because it is equivalent to obj2 in terms of not having a prototype function. It just binds this differently (In obj1 and obj1 this is determined "by the invocation, but not by the enclosing context" and in obj3 this is lexically bound to the window object. Both is nicely described in this article.).

The code snippet:

// Using the basic method definition
const obj1 = {
  foo: function() {
    console.log("This is foo");
  },
  bar: function() {
    console.log("This is bar");
    this.foo();
  }
};

// Using shorthand method syntax
const obj2 = {
  foo() {
    console.log("This is foo");
  },
  bar() {
    console.log("This is bar");
    this.foo();
  }
};

// Using arrow function
const obj3 = {
  foo: () => console.log("This is foo"),
  bar: () => {
    console.log("This is bar"); this.foo();
  }
};


/* Test */
obj1.bar(); // works!
obj2.bar(); // works!
obj3.bar(); // throws TypeError (this.foo is not a function)

How I found that func1 is a prototype function and func2 not:

I looked at both in the console of Chrome Dev Tools and found the prototype object only contained in one of them:

I looked at this and this question about the difference between __proto__ and prototype but my question here is about why the later is not present after using a syntax which should be equivalent.

回答1:

Why does obj1.bar contain the .prototype Object and obj2.bar does not?

Because it's a method definition. Methods are no constructors, they don't need one. (It's the same for class methods and for arrow functions, btw.)
In obj2 you used a function expression, which creates a function that can be used as a constructor (as has been always the case in ES5).

Are all three objects prototype objects?

An object is not a "prototype object". Every object can be used as the prototype of some other object or not.

Why does the fact of obj2.bar not having a .prototype not influence the way in which it binds this?

Why would it? It's still a method that is supposed to have a dynamic this value, otherwise it could not be shared.

Only the arrow functions that you used in obj3 have special behaviour in this regard. See Methods in ES6 objects: using arrow functions for details.