wawanopoulos wawanopoulos - 11 days ago 5
Javascript Question

Declare parameter into function scope

I'am trying to declare a parameter into an app constructor but it raise an exception..

var app = {

// Where can i declare this param and how ?
this.param1 : null,

oneFunction: function() {
// use param1 here..
},

secondFunction: function() {
// use param1 here..
}
}


How can i declare this param to use it into functions ?

Answer

You don't need the this. The param1 can be defined as a property of your object as below.

var app = {

    param1 : null,

    oneFunction: function() {
        // use param1 here..
    },

    secondFunction: function() {
        // use param1 here..
    }
}

Regarding the use param1 in your function, you can access it as this.param1. The this would refer to the app object.

For a plain example please have a look at the following snippet:

var app = {

    param1 : null,

    oneFunction: function() {
        this.param1 = 4;
    },

    secondFunction: function() {
        console.log(this.param1);
    }
}

app.oneFunction();
app.secondFunction();