Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access object property from inside class function [duplicate]

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).

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.

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

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

(sorry for my english...)

like image 342
Ivan Seidel Avatar asked Aug 06 '12 03:08

Ivan Seidel


People also ask

How do you access object properties dynamically?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique.


1 Answers

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

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();
        });
    };
}
like image 115
Polyov Avatar answered Nov 15 '22 21:11

Polyov