JavaScript中的私有和公共方法及变量

时间:2013-05-09 08:34:50

标签: javascript private-members private-methods public-method

我有一些问题需要了解如何使用私有/公共方法实现和使用类并使用它,即使在阅读之后也是如此。

我有以下代码:

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”将是公共方法,而“Floors”,“str”和“Components”将是私有变量。 我认为我将变量设为私有,“进程”和“InitVariables”是私有的,但“getFloor”方法没有成功。

现在,“警报(楼层);”在“警报(地板);”时向我显示正确答案没有显示任何东西。 我的问题: 1.我怎样才能补充“getFloors”? 2.我是否编写好代码或者我应该更改代码?

1 个答案:

答案 0 :(得分: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())

希望有所帮助:)