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.