0

我在理解如何使用私有/公共方法实现和使用类并使用它时遇到了一些问题,即使经过一些阅读。

我有以下代码:

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());

我希望“process”和“InitVariables”是私有方法,“getFloors”是公共方法,而“Floors”、“str”和“Components”是私有变量。我想我将变量设为私有,并将“进程”和“InitVariables”设为私有,但使用“getFloor”方法没有成功。

现在,“警报(楼层);” 在 "alert(Floors);" 时显示正确答案 不显示任何东西。我的问题: 1. 我怎样才能实现“getFloors”?2. 代码写得好还是该改?

4

1 回答 1

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())

希望能帮助到你 :)

于 2013-05-09T10:24:32.543 回答