javascript javascript中的类方法不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16063549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class method in javascript is not a function
提问by mlwacosmos
The answer must be obvious but I dont see it
答案一定很明显,但我没看到
here is my javascript class :
这是我的 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;
};
};
then I instanciate
然后我实例化
var auth = new Authentification();
alert(Authentification.ACCESS_MASTER);
alert(auth.componentAvailable);
alert(auth.isComponentAvailable());
I can reach everything but the last method, it says in firebug :
除了最后一种方法之外,我可以访问所有内容,它在 firebug 中说:
auth.isComponentAvailable is not a function.. but it is..
auth.isComponentAvailable 不是函数.. 但它是..
Thank you
谢谢
回答by dm03514
isComponentAvailable
isn't attached to (ie is not a property of) your object, it is just enclosed by your function; which makes it private.
isComponentAvailable
不附加到(即不是属性)您的对象,它只是被您的函数包围;这使它成为私有的。
You could prefix it with this
to make it pulbic
你可以this
在它前面加上前缀以使其公开
this.isComponentAvailable = function() {
this.isComponentAvailable = function() {
回答by cfs
isComponentAvailable
is a private function. You need to make it public by adding it to this
like so:
isComponentAvailable
是一个私有函数。您需要将其添加为公开,this
如下所示:
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923";
this.isComponentAvailable = function() {
...
};
};
回答by Nolo
Another way to look at it is:
另一种看待它的方法是:
var Authentification = function() {
// class data
// ...
};
Authentification.prototype = { // json object containing methods
isComponentAvailable: function(){
// returns a value
}
};
var auth = new Authentification();
alert(auth.isComponentAvailable());
回答by Stone Shi
isComponentAvailable is actually attached to the window object.
isComponentAvailable 实际上是附加到 window 对象上的。