javascript 如何从类函数内部访问对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11822234/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:27:09  来源:igfitidea点击:

How to access object property from inside class function

javascriptclassobject

提问by Ivan Seidel

one of my classes in Javascript needs to be "updated" with Json sometimes. I have always done a function, that updates the array of data, given an id, but now i wanted to do it more encapsulated (Function update, inside the class).

我在 Javascript 中的一个类有时需要使用 Json 进行“更新”。我一直在做一个函数,它更新数据数组,给定一个 id,但现在我想做更多的封装(函数更新,在类中)。

What i made:

我做了什么:

function File(data){
        this.data = data;

        this.update = function (callback){
            var set = function(ajaxData){
                this.data = ajaxData.PcbFile;
            }
            getPcbFile(data.id, function(ajaxData){
                set(ajaxData);
                callback();
            });
        };
    }

But, this.data = ajaxData.PcbFile;doesen't work... My object still with the last data set, and not the updated one. The function SET, i created as another attempt to set the data.

但是,this.data = ajaxData.PcbFile;不起作用...我的对象仍然使用最后一个数据集,而不是更新的数据集。函数 SET,我创建的另一个尝试设置数据。

There is no problem on the ajax, since i debuged the ajaxData, and it's ok (when i update).

ajax没有问题,因为我调试了ajaxData,没问题(更新时)。

So, how do i really access the object property datafrom an inside function?

那么,我如何真正data从内部函数访问对象属性?

(sorry for my english...)

(对不起我的英语不好...)

回答by Polyov

I learned this the hard way, you have to be careful with this. It always refers to the thisin the current scope, not it's containing object. Whenever you wrap something in function() { ... }, thisbecomes of a different scope. In your case, duplicate the object to a local variable and manipulate it's .dataproperty.

我是通过艰难的方式学会了这一点,你必须小心使用this. 它总是指this当前范围内的 ,而不是它包含的对象。每当您将某些东西包装在 中时function() { ... }this就会变成不同的范围。在您的情况下,将对象复制到局部变量并操作它的.data属性。

function File(data){
    this.data = data;
    var file = this; //call the variable whatever you want
    this.update = function (callback){
        var set = function(ajaxData){
            file.data = ajaxData.PcbFile;
        }
        getPcbFile(data.id, function(ajaxData){
            set(ajaxData);
            callback();
        });
    };
}

回答by elclanrs

Cache thisso you can refer to it in the same context some place else:

缓存,this以便您可以在其他地方的相同上下文中引用它:

function File(data){

  var self = this;

  self.data = data;

  self.update = function (callback){
    var set = function(ajaxData){
      self.data = ajaxData.PcbFile;
    }
    getPcbFile(data.id, function(ajaxData){
      set(ajaxData);
      callback();
    });
  };
}

回答by nnnnnn

Try this:

试试这个:

function File(data){
    this.data = data;

    var self = this;

    this.update = function (callback){
        var set = function(ajaxData){
            self.data = ajaxData.PcbFile;
        }
        getPcbFile(data.id, function(ajaxData){
            set(ajaxData);
            callback();
        });
    };
}

The value of thiswithin a function depends on how that function is called. E.g., when you use the "dot" notation, someObj.someMethod()then within someMethod()you'd have thisset to someObj. You can explicitly set thisto some other object using the .apply()or .call()methods. Otherwise if you call a function as with set(ajaxData)then thiswill be the global object (window).

this的函数内取决于函数是如何被调用。例如,当您使用“点”记号,someObj.someMethod()然后里someMethod()你必须this设置为someObj。您可以this使用.apply().call()方法显式设置为某个其他对象。否则,如果您像 withset(ajaxData)那样调用函数,this则将是全局对象 ( window)。

By keeping a reference to thisoutside your function (I prefer the variable name selffor this purpose) you can reference it inside your function.

通过保留对this函数外部的引用(self为此我更喜欢变量名),您可以在函数内部引用它。

回答by Sergio Abreu

 (function(){
   var accessible = {
     prop1: 'blabla',
     verify: function(){
       console.log( this.prop1);
       return this;
     },
     deepAccess: function(){
       return function(){
         accessible.prop1 = 'bloblo';
         return function(){
           console.log("Deep access ", accessible.prop1);
         }
       }
     },
     insideFunction: function(){
       //here you can use both 'this' or 'accessible' 
                  this.prop1 = 'bleble';
                  return this;
       },
       prop2: 3.1415
    };
   return accessible;
})().verify().insideFunction().verify().deepAccess()()();

/* console shows:
 blabla
 bleble
 Deep access bloblo
*/