Using super in an object created using Object.create

This morning I stumbled upon a tweet from Šime Vidas , where he presented the following use case superfor object literals:

let A = {
  run() {
    console.log('A runs');
  }
};

let B = {
  run() {
    super.run();
  }
};

Object.setPrototypeOf(B, A);

B.run(); // A runs

This works, and the assignment seems to B.__proto__ = A;work in both Firefox and Chrome.

So, I decided that I can do the same with Object.create:

let A = {
  run() {
    console.log('A runs');
  }
};

let B = Object.create(A);
B.run = function() { super.run() };

Unfortunately, this leads to an error in Firefox:

SyntaxError: using super-properties is only available within methods or eval code in methods

And Chrome:

Untrained SyntaxError: the keyword “super” is unexpectedly here

The same thing happens when I try to pass a property descriptor object to the second argument Object.create.

, , , ( - ?).

, ( )? - , Object.create, ?

+4
3

-, ES2015, , twitter.

?

" " def obj lit http://tc39.imtqy.com/ecma262/#sec-function-definitions-static-semantics-early-errors

Static Semantics: Early Errors , :

  • , FormalParameters SuperProperty, .
  • , FunctionBody SuperProperty. .
  • , FormalParameters SuperCall, .
  • , FunctionBody SuperCall.

, , . , .

?

, super . http://tc39.imtqy.com/ecma262/#sec-runtime-semantics-definemethod

, , , :

let B = {
  run() {
    super.run();
  },
  walk() {
    console.log(typeof this.run);
  }
};

var run = B.run;
run(); // the 'super' binding still works, thanks to the internal MakeMethod

var walk = B.walk;
walk(); // 'undefined': the 'this' binding on the other hand is lost, as usual

7 , , :

  1. MakeMethod (, ).

?

. . b/c

, , - .toMethod, super, , Object.create .

+4

. super , , . , -

let B = {
    __proto__: A,
    run(){
        super.run();
    }
};

A Object.setPrototypeOf(B, A).

+1

I mean, you can do this:

let A = {
  run() {
    console.log('A runs');
  }
};

let B = {
  run() {
    super.run();
  }
};

Object.setPrototypeOf(B, A);

let C = Object.create(B);
C.run(); //A runs

By the way, this also fails:

let A = {
  run() {
    console.log('A runs');
  }
};

let B = {
  run: function() {
    super.run(); // 'super' keyword unexpected here
  }
};

Object.setPrototypeOf(B, A);

B.run();
0
source

All Articles