Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

ecmascript 6 - Javascript: What's the difference between .call() and super()?

What's the difference between .call() and super()? Is super() just an es2015 thing? Or does .call() have more functionality?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • super() calls the constructor of the class you extened

    class Foo extends Bar {
      constructor() {
        super();  // calls Bar's constructor
      }
     }
    
  • call is a generic function you can use with any function

    function a() { console.log(this); };
    function b() { console.log(this); };
    function c() { console.log(this}; };
    
    a.call("hello");
    b.call(123);
    c.call({});
    
  • super knows which class you inherited from and automatically passes the correct this.

    class Foo extends Bar {
      constructor() {
        super();  // calls Bar's constructor
      }
    }
    
  • call requires you to be explicit.

    class Foo extends Bar {
      constructor() {
        Bar.call(this);  // You had explicitly specify 'Bar' 
                         // and explicitly pass 'this'
      }
    }
    
  • super lets you call functions on the parent implicitly

    class Bar {
      log() { 
        console.log("bar-log");
      }
    }
    
    class Foo extends Bar {
      log() {
        super.log();
      }
    }
    
  • call requires you to be explicit

    class Bar {
      log() { 
        console.log("bar-log");
      }
    }
    
    class Foo extends Bar {
      log() {
        Bar.prototype.log.call(this);  // Explicitly reference bar's log function
                                       // and explicitly specify 'this'
      }
    }
    

I think you could argue super offers a subset of the functionality of call. Some might call it syntactic sugar meaning you can use call everywhere you can use super, super is just easier because it implicitly calls stuff from the class you extended/inherited from (technically the next thing up the prototype chain?) and because it implicitly passes this for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...