JS: Confusion about inheritance

后端 未结 4 551
轮回少年
轮回少年 2020-12-17 02:32

I am familiar with OOP concepts through the languages like C++, Java. Right now I am trying to learn JavaScript as a hobby, mainly due to the interest in WebGL. But I am hav

4条回答
  •  清歌不尽
    2020-12-17 03:06

    @@@ 2. Derived.prototype = new Base; is creating an instance of Base and this will remain in memory always (assuming Derived is defined in global space). What to do if Base class is very costly and I don't want an extra object?

    Yea. This example is a inheritance-learning style. For using in your application, try:

        function F() {}
        F.prototype = Base.prototype; // Linking to Base's prototype
    
        Derived.prototype = new F(); // The least memory-consumption object.
        Derived.prototype.constructor = Base; // Constructor reference correction
    

    @@@ 1. What to do with data members in prototype object (_n in this example)?

    Using the above prototype-chain, we are not creating any instance of Base. So, this question is invalidated.

提交回复
热议问题