Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - Why does a method using the shorthand method syntax not contain a prototype object

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...