0

我有一些問題,以瞭解如何實現和使用私有/公共方法的類並使用它,即使在一些閱讀後。私有和公共方法和JavaScript中的變量

我有以下代碼:

var _Exits = 0; 
var _Shuttles = 0; 

function Parking(_str) 
{ 
var Floors = 0; 
var str = _str; 
var Components = null; 

function process() 
{ 
    var Exit = new Array(); 
    Exit.push("exit1" + str); 
    Exit.push("exit2"); 
    var Shuttle = new Array(); 
    Shuttle.push("shuttle1"); 
    Shuttle.push("shuttle2"); 
    Components = new Array(); 
    Components.push(Exit, Shuttle); 
} 

function InitVariables() 
{ 
    var maxFloors = 0; 

    _Exits = (Components[0]).length; 
    _Shuttles = (Components[1]).length; 

    /* 
    algorithm calculates maxFloors using Componenets 
    */ 

    Floors = maxFloors; 
} 

//method runs by "ctor" 
process(str); 
InitVariables(); 
alert(Floors); 
} 

Parking.prototype.getFloors = function() 
{ 
return Floors; 
} 

var parking = Parking(fileString); 
alert("out of Parking: " + parking.getFloors()); 

我想要的「過程」和「InitVariables」將是私有方法和「的getFloors」將是公共方法,而「地板」,「海峽」和「組件「將是私人股權。 我想我使變量private和「process」和「InitVariables」是私人的,但沒有成功的使用「getFloor」方法。

現在,「警報(樓層);」向我展示正確的答案,同時提醒(樓層);「沒有顯示任何東西。我的問題: 1.如何補充「getFloors」? 2.我編寫的代碼是否正確,或者我應該更改它?

+0

的可能重複[如何在構造函數中設置javascript私有變量?](http://stackoverflow.com/questions/6799103/how-to-set-javascript-private-variables-in-constructor) – 2014-02-14 03:21:44

回答

1

我還沒有測試此代碼,但它應該幫助你理解如何實現與私營和公共成員JavaScript類:

var Parking = (function(){ 
    "use strict"; //ECMAScript 5 Strict Mode visit http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ to find out more 

    //private members (inside the function but not as part of the return) 
    var _Exits = 0, 
    _Shuttles = 0, 
    // I moved this var to be internal for the entire class and not just for Parking(_str) 
    _Floors = 0; 

    function process() 
    { 
     var Exit = new Array(); 
     Exit.push("exit1" + str); 
     Exit.push("exit2"); 
     var Shuttle = new Array(); 
     Shuttle.push("shuttle1"); 
     Shuttle.push("shuttle2"); 
     Components = new Array(); 
     Components.push(Exit, Shuttle); 
    }; 

    function InitVariables() 
    { 
     var maxFloors = 0; 
     _Exits = (Components[0]).length; 
     _Shuttles = (Components[1]).length; 

     /* 
     algorithm calculates maxFloors using Componenets 
     */ 
     _Floors = maxFloors; 
    } 

    function Parking(_str) 
    { 
     // Floors was internal to Parking() needs to be internal for the class 
     //var Floors = 0; 
     var str = _str; 
     var Components = null; 
     //method runs by "ctor" 
     process(str); 
     InitVariables(); 
     alert(_Floors); 
    } 

    //public members (we return only what we want to be public) 
    return { 
     getFloors: function() { 
      return _Floors; 
     } 
    } 
}).call(this) 

console.log(Parking.getFloors()) 

希望它能幫助:)