1

I've got two functions, each with a variable called s (In this case). When I instantiate one function it's fine, but when I instantiate the other one right after, the second one overrides the first's s.

Code:

t1 = function(){
    s = 2;

    Object.defineProperty(this, "test", {
        value: function(){
            console.log(s);
        },
        configurable: false
    });
}
t2 = function(){
    s = 42;

    Object.defineProperty(this, "test", {
        value: function(){
            console.log(s);
        },
        configurable: false
    });
}

var t = new t1()
t.test(); // 2

var y = new t2();
y.test(); // 42

t.test(); // 42

Why is this, and how can I fix it?

Mobilpadde
  • 1,871
  • 3
  • 22
  • 29
  • 1
    http://www.w3schools.com/js/js_scope.asp The variable 's' is automatically globally defined. Hence they are the same variable. That is why the latter overrides the former. – user1071979 Dec 04 '15 at 22:15

3 Answers3

4

The problem is that s is from the global scope. To define a variable s inside your function, declare it with

var s = 2;

To avoid such errors, you can add the line

"use strict"; 

to the beginning of your file. This way accessing an undeclared variable in the global scope will be forbidden.

lex82
  • 11,173
  • 2
  • 44
  • 69
2

because s becomes a global variable, set var before each s.

1

You're referencing s from somewhere outside of the functions' scopes this means that, they will share that variable because it does not get redeclared within their own scopes.

Try this:

t1 = function(){
    var s = 2;

    Object.defineProperty(this, "test", {
        value: function(){
            console.log(s);
        },
        configurable: false
    });
}
t2 = function(){
    var s = 42;

    Object.defineProperty(this, "test", {
        value: function(){
            console.log(s);
        },
        configurable: false
    });
}
simon
  • 1,095
  • 6
  • 11