https://bigfrontend.dev/quiz/method
What does the code snippet below output by console.log
?
// This is a trick question
// case 1
const obj1 = {
foo() {
console.log(super.foo());
},
};
Object.setPrototypeOf(obj1, {
foo() {
return 'bar';
},
});
obj1.foo();
// case 2
const obj2 = {
foo: function () {
console.log(super.foo());
},
};
Object.setPrototypeOf(obj2, {
foo() {
return 'bar';
},
});
obj2.foo();
// case 1
const obj1 = {
foo() {
console.log(super.foo());
},
};
Object.setPrototypeOf(obj1, {
foo() {
return 'bar';
},
});
obj1.foo(); // didn't run because of the error caused by the second case
// case 2
const obj2 = {
foo: function () {
console.log(super.foo());
},
};
Object.setPrototypeOf(obj2, {
foo() {
return 'bar';
},
});
obj2.foo(); // Error: 'super' keyword unexpected here
We can use either the ES6 shorthand syntax propertyName() {}
or propertyName: function() {}
to define "methods" on object literals. However, they are not fully identical. Only the shorthand syntax propertyName() {}
is a Method Definition. propertyName: function() {}
is just a property, not a method. In JavaScript, starting with ES6, a method is defined as a function that has an internal [[HomeObject]]
property containing the object to which the method belongs. The [[HomeObject]]
property is used by super
to resolve the parent prototype and its methods.