Prototype for private sub-methods

前端 未结 3 1499

I have code that looks like this:

var baseClass = function() {
// CODE
    var subClass = function() {
        // MORE CODE
    }
}

Adding meth

3条回答
  •  不思量自难忘°
    2021-01-26 03:40

    Why do you declare that subclass in the base class? Doesn't make sense to me.

    You can add to the subclass's prototype whereever it is in you scope. In your code it would be

    var baseClass = function() {
    // CODE
        var subClass = function() {
            // MORE CODE
        }
        subClass.prototype = {
            ...
        }
    }
    

    But I'd suggest to put it out of the base class constructor. If you want it private for some reason, add a closure:

    (function(){
    
        baseClass = function() { // public
            // CODE
        }
        baseClass.prototype = {...};
    
        var subClass = function() { // private
            // MORE CODE
        }
        subClass.prototype = Object.create(baseClass.prototype);
        subClass.prototype.newMethod = function () { ... }
    })()
    

    EDIT to answer the extended question:

    Ah, subClass doesn't inherit from baseClass! We had expected that, otherwise it may be OK to have it inside the constructor. Then, the same prototype could have been added to each of the different subClass constructors:

    var subproto = {
        method_b: = function(){
            // manipulate "this"
        },
        ...
    };
    function baseClass() {
        // some code
        function sub() {
            // is a constructor for subs which belong to this specif base intance
            ...
        }
        sub.prototype = subproto; // the sub constructors of each base instance
                                  // have the same prototype
        var x = new sub(),
            y = new sub(); // example usage of the sub constructor
    }
    baseClass.prototype = {...}
    

    Else, if you want one common sub constructor (outside of function baseClass), you may give the base instance the sub belongs to as an argument to the constructor - as you did. Of course the sub (both internal and external methods) can only access public properties of that base instance.

    The mistake you made in your rearranged code is that your prototype ("external") methods tried to access the private parent variable from the sub constructor. As you say, "error saying parent isn't defined".

    var subClass = function(parent) {
        var sub = this;
        this.parent = parent; // make it public
        this.property_c = 1;
        this.method_a = function() {
            return sub.property_c + parent.property_a;
        }
        // MORE CODE
    }
    subClass.prototype.method_b = function(){
        // prototype functions can only access public properties
        // i.e. privileged methods, public attributes and other prototype properties
        return this.property_c + this.parent.property_b;
    }
    

提交回复
热议问题