Question

I have written a code to get and set local variable in a javascript function; it's not working.

function wrapper() {
    var x = 10;
    this.getX = function () {
        return x; //Return x
    }
    this.setX = function (newX) {
        x = newX; //Set value for x
    }
}

var obj = wrapper();

obj.getX(); //Get value of x in wrapper
obj.setX(25); //Set value of x in wrapper

How to get and set local variables in javascript function from external code.

Was it helpful?

Solution

Call wrapper as a constructor function.

var obj = new wrapper();

… so that this is "an instance of wrapper" and not "the default object, window".

Convention dictations that constructor functions are named with a capital letter, so all change wrapper to Wrapper throughout your program.

For further reading, see MDN on new.

OTHER TIPS

var wrapper = {
    x: 0,
    getX: function(){ return this.x;},
    setX: function(x){this.x=x;}
}

var obj = wrapper;

obj.getX(); //Get value of x in wrapper
obj.setX(25); //Set value of x in wrapper
alert(obj.getX());

or better:

function wrapper(){
    this.x = 0;
    this.getX = function(){ return this.x;};
    this.setX = function(x){this.x=x;};
}

var obj = new wrapper();

obj.getX(); //Get value of x in wrapper
obj.setX(25); //Set value of x in wrapper
alert(obj.getX());

Yeah, as i think you need to do the "new" for creating an instance. Javascript does not have the keyword "class" like other languages. This means, it depends on how you use the "function". If you use it just like you would, you use it like a function would return toe result in obj. To use it as class-instance you have to create the instance with new.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top