简体   繁体   English

无法访问类成员

[英]Can't access class member

function Example(){
     var id;
};

Example.prototype.getId = function(){
     // return this.id; 
};

Example.prototype.init = function(){
   $.post( 'generateId.php', {}, function(data){
       // this.id = data; 
   });   
};

How can I access id within these functions? 如何在这些功能中访问id?

It seems that you think "private" variables exist in Javascript. 您似乎认为Javascript中存在“私有”变量。 Private variables are only emulated in Javascript through closures, but do not exist as in other languages. 私有变量仅通过闭包在Javascript中模拟,但不像其他语言那样存在。 In your code, id is only accessible from within your constructor. 在您的代码中,只能从构造函数中访问id

You can keep id private though, and still be able to access it from within your functions, but you'll have to declare those functions in your constructor as closures to have access to it: 你可以保持id私有,但仍然可以从你的函数中访问它,但是你必须在构造函数中声明这些函数作为闭包来访问它:

function Example()
{
    //private
    var id;

    this.getId = function ()
    {
        return id;
    }

    this.init = function()
    {
       $.post( 'generateId.php', {}, function(data)
       {
           id = data;
       });   
    };
};

Another problem is that you're trying to access this from within an asynchronous callback. 另一个问题是您尝试从异步回调中访问this In this context (the callback passed to $.post ), this is whatever the context of the calling function was, which is probably undefined or the XmlHTTPRequest object. 在此上下文中(传递给$.post的回调), this是调用函数的上下文,可能是未定义的或XmlHTTPRequest对象。

If you want to access it, you'll have to cache the this of you function (from your original code, assuming id is not private): 如果你想访问它,你必须缓存你的this功能(从你的原始代码,假设id不是私有的):

Example.prototype.init = function()
{
   var self = this;
   $.post( 'generateId.php', {}, function(data)
   {
       self.id = data;
   });   
};

Maybe you can rewrite a bit: 也许你可以改写一下:

var Example = Example || {};
Example.id = "";

Example.init = function(){
$.post( 'generateId.php', {}, function(data)
{
   Example.id = data; // <-------- error
});  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM