1

When my object method is function declaration super keyword work normally.

const user = {
  name: "Murad"
};
const murad = {
  getName() {
    super.name
  },
  __proto__: user
};

But when I want to change function declaration to function expression JS return Error

const user = {
  name: "Murad"
};
const murad = {
  getName: function() {
    super.name
  },
  __proto__: user
};

Uncaught SyntaxError: 'super' keyword unexpected here Why this happpened?

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Murad Sofiyev
  • 790
  • 1
  • 8
  • 25

1 Answers1

0

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals. super MDN

In the first example it is used in a method so a valid expression

const user = {
  name: "Murad"
};
const murad = {
  getName() {
    return super.name
  },
  __proto__: user
};

console.log(murad.getName())

Second one is not a method syntax as per ECMAScript Method definition section

const user = {
  name: "Murad"
};
const murad = {
  getName: function() {
    super.name
  },
  __proto__: user
};
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • This is so weird actually you say first is method but second property is which have value. But you can see in MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) there are same thing. First one only shorthand. – Murad Sofiyev Sep 26 '19 at 01:38
  • @MuradSofiyev wait let me update it in more sensible manner – Code Maniac Sep 26 '19 at 01:42
  • 1
    @MuradSofiyev MDN doesn't say that they are the same thing. It says that one can be shortened to the other. – Bergi Sep 26 '19 at 02:15