[removed] Calling private method from prototype method

后端 未结 3 1299
你的背包
你的背包 2021-01-30 18:08

I am sure that this must be a pretty common question but after scouring the internets for several hours, I have not found an answer. Here is the question:

Suppose that

3条回答
  •  借酒劲吻你
    2021-01-30 18:57

    It's not possible. If you need access to private variables/functions, you must use privileged (helper) functions.

    It sometimes is possible to use helper functions in a local closure scope instead of private helper functions (in the constructor scope), which would be accessible from prototype functions. See Alex Wayne's or Raynos' answers for that.

    You said:

    I cannot make the eat function a privaliged function because in order for prototype inheritance to work it needs to be part of the prototype.

    Why not?

    MammalPrototype = {
        eat: function() {},
        sleep: function() {}
    };
    
    function Dog(color) {
        ...
        this.eat = function() {
            ... // using private functions
            MammalPrototype.eat.call(this, options) // ?
        };
    };
    Dog.prototype = Object.create(MammalPrototype); // inherit from an object
    

    new Mammal() is OK when Mammal really is only a empty function. See https://stackoverflow.com/a/5199135/1048572 for how this works. The shim proposed there is of course not what a native implementation does, but it is exactly what we need here. Do not create a instance just to inherit from it!

    Dog.prototype.sleep = function() {
        ... 
    };
    
    function Dalmatian() {
        Dog.call(this, "black.white");
        ...
    }
    Dalmatian.prototype = Object.create(Dog.prototype); // sic
    Dalmatian.prototype.xyz = function() {};
    

    To call the super constructor on this means to receive all privileged methods, and their functionality. You will need to do this if you are using private variables and/or functions in "classes" you inherit from, otherwise all calls to inherited privileged functions will affect only the one instance you've set your prototype to.

提交回复
热议问题