Classical Vs prototypal inheritance

前端 未结 3 1952
广开言路
广开言路 2020-11-30 01:43

After reading about both, I just have curiosity, how programming community uses this? In what situation which?

3条回答
  •  粉色の甜心
    2020-11-30 01:46

    Since Javascript doesn't support "Classic" inheritance as most would understand (and you haven't given any references to what you've been reading) I'll assume you mean inheritance handled like this:-

     function base() {
        var myVar;
        this.someBaseFunc = function() { }
     }
    
    
     function derived() {
        base.call(this);
        var someOtherVar;
        this.SomeOtherFunc = function() { }
     }
    

    My general rule of thumb is:

    • If the Classes are complex and the instances are few use a "classical" approach. This allows the classes to expose publicly only those features that should be made public.
    • If the Class are simple and the instances are many use a prototypal approach. This limits the overhead of defining and storing references to functions over and over again as instances are created.

提交回复
热议问题