JavaScript private methods

前端 未结 30 1876
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:16

To make a JavaScript class with a public method I\'d do something like:

function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something         


        
30条回答
  •  臣服心动
    2020-11-22 08:55

    There are many answers on this question already, but nothing fitted my needs. So i came up with my own solution, I hope it is usefull for someone:

    function calledPrivate(){
        var stack = new Error().stack.toString().split("\n");
        function getClass(line){
            var i = line.indexOf(" ");
            var i2 = line.indexOf(".");
            return line.substring(i,i2);
        }
        return getClass(stack[2])==getClass(stack[3]);
    }
    
    class Obj{
        privateMethode(){
            if(calledPrivate()){
                console.log("your code goes here");
            }
        }
        publicMethode(){
            this.privateMethode();
        }
    }
    
    var obj = new Obj();
    obj.publicMethode(); //logs "your code goes here"
    obj.privateMethode(); //does nothing
    

    As you can see this system works when using this type of classes in javascript. As far as I figured out none of the methods commented above did.

提交回复
热议问题