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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…