javascript中的类方法不是函数

Class method in javascript is not a function

本文关键字:函数 类方法 javascript      更新时间:2023-09-26

答案肯定是显而易见的,但我没有看到它

这是我的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中说:

身份验证。isComponentAvailable不是一个函数

. .

isComponentAvailable不是附加到(即不是属性)你的对象,它只是由你的功能封闭;所以它是私人的。

你可以用this作为前缀使它成为公共的

this.isComponentAvailable = function() {

isComponentAvailable实际上是附加在window对象上的

isComponentAvailable为私有函数。您需要将其添加到this,使其公开,如下所示:

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

另一种看待它的方式是:

var Authentification = function() {
    // class data
    // ...
};
Authentification.prototype = {    // json object containing methods
    isComponentAvailable: function(){
        // returns a value
    }
};
var auth = new Authentification();
alert(auth.isComponentAvailable());