1

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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());

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.