[removed] Calling private method from prototype method

后端 未结 3 1301
你的背包
你的背包 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 19:06

    When an object (child object) inherits from another object (parent object) how should children methods use helper functions and is it possible to make these private?

    You need some layers of abstraction to achieve what you want: Live Example

    Uses klass

    var Mammal = klass(function (privates) {
        privates.local_helper = function () {
            console.log("local_helper invoked"); 
        }
    
        return {
            constructor: function () {
                console.log("mammal constructed");
                privates(this).caneat = true;
            },
            eat: function () { 
                privates.local_helper();
                console.log("mammal eat");
            },
            sleep: function () { 
                console.log("mammal sleep");
            } 
        }; 
    });
    
    var Dog = klass(Mammal, function (privates, $super) {
        return {
            constructor: function () {
                $super.constructor.call(this);
                console.log("dog constructed"); 
            },
            eat: function () {
                $super.eat.call(this);
                privates.local_helper();
                console.log("dog eat");
                console.log(privates(this).caneat);
            }
        };
    });
    
    var dog = new Dog();
    dog.eat();
    

提交回复
热议问题