Skip to content

Latest commit

 

History

History
96 lines (68 loc) · 1.92 KB

51.method.md

File metadata and controls

96 lines (68 loc) · 1.92 KB

51. method

Problem

https://bigfrontend.dev/quiz/method

Problem Description

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();

Answer

// 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

Explanation

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.

Reference