JavaScript private methods

前端 未结 30 1870
-上瘾入骨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条回答
  •  萌比男神i
    2020-11-22 08:42

    Here's what i enjoyed the most so far regarding private/public methods/members and instantiation in javascript:

    here is the article: http://www.sefol.com/?p=1090

    and here is the example:

    var Person = (function () {
    
        //Immediately returns an anonymous function which builds our modules 
        return function (name, location) {
    
            alert("createPerson called with " + name);
    
            var localPrivateVar = name;
    
            var localPublicVar = "A public variable";
    
            var localPublicFunction = function () {
                alert("PUBLIC Func called, private var is :" + localPrivateVar)
            };
    
            var localPrivateFunction = function () {
                alert("PRIVATE Func called ")
            };
    
            var setName = function (name) {
    
                localPrivateVar = name;
    
            }
    
            return {
    
                publicVar: localPublicVar,
    
                location: location,
    
                publicFunction: localPublicFunction,
    
                setName: setName
    
            }
    
        }
    })();
    
    
    //Request a Person instance - should print "createPerson called with ben"
    var x = Person("ben", "germany");
    
    //Request a Person instance - should print "createPerson called with candide"
    var y = Person("candide", "belgium");
    
    //Prints "ben"
    x.publicFunction();
    
    //Prints "candide"
    y.publicFunction();
    
    //Now call a public function which sets the value of a private variable in the x instance
    x.setName("Ben 2");
    
    //Shouldn't have changed this : prints "candide"
    y.publicFunction();
    
    //Should have changed this : prints "Ben 2"
    x.publicFunction();
    

    JSFiddle: http://jsfiddle.net/northkildonan/kopj3dt3/1/

提交回复
热议问题