15

答案一定很明显,但我看不到

这是我的 javascript 类:

var Authentification = function() {
        this.jeton = "",
        this.componentAvailable = false,
        Authentification.ACCESS_MASTER = "http://localhost:1923",

        isComponentAvailable = function() {
            var alea = 100000*(Math.random());

            $.ajax({
               url:  Authentification.ACCESS_MASTER + "/testcomposant?" + alea,
               type: "POST",
               success: function(data) {
                   echo(data);
               },
               error: function(message, status, errorThrown) {
                    alert(status);
                    alert(errorThrown);
               }
            });

            return true;
        };
    };

然后我实例化

var auth = new Authentification();

alert(Authentification.ACCESS_MASTER);    
alert(auth.componentAvailable);
alert(auth.isComponentAvailable());

除了最后一种方法,我什么都能用,它在 firebug 中说:

auth.isComponentAvailable 不是一个函数.. 但它是..

谢谢

4

4 回答 4

18

isComponentAvailable不附加到您的对象(即不是其属性),它只是被您的函数所包围;这使它成为私有的。

您可以在它前面加上前缀this以使其公开

this.isComponentAvailable = function() {

于 2013-04-17T15:03:50.770 回答
4

isComponentAvailable is actually attached to the window object.

于 2013-04-17T15:27:25.140 回答
2

isComponentAvailable是一个私有函数。您需要通过添加它来公开它this

var Authentification = function() {
    this.jeton = "",
    this.componentAvailable = false,
    Authentification.ACCESS_MASTER = "http://localhost:1923";

    this.isComponentAvailable = function() {
        ...
    };
};
于 2013-04-17T15:03:52.683 回答
2

另一种看待它的方式是:

var Authentification = function() {
    // class data
    // ...
};

Authentification.prototype = {    // json object containing methods
    isComponentAvailable: function(){
        // returns a value
    }
};

var auth = new Authentification();
alert(auth.isComponentAvailable());
于 2013-04-17T15:10:59.457 回答