subclass.prototype = new superclass() vs. subclass = new superclass()

后端 未结 3 985
醉话见心
醉话见心 2020-12-28 23:59

I\'ve been instantiating subclasses in javascript using

object = new class ()

but I notice some people instantiate using

ob         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 00:19

    The difference is that when you do:

    var subclass = new superclass();
    

    you are creating an instance of superclass. subclass is just variable. You are not creating a sub-class (ie. making subclass inherit superclass). In the latter example, assuming subclass is a function, you are saying that all new instances of subclass should inherit (ie. sub-class) superclass.

    So:

    function superclass() {this.stuff="stuff";}
    function subclass() {}
    subclass.prototype = new superclass();
    alert(new subclass().this); // pops up "stuff"
    

    is prototypical inheritance.

    As for the new operator, it is used for creating an instance of built-in objects and user defined types. A user defined type is simply a function.

    Edit: When I wrote above that subclass inherits supertype using prototypical inheritance, I mean that all new instances of subclass inherit from one particular instance of superclass, not from the superclass type/function itself.

提交回复
热议问题