0

I am very new to javascript, and I would like to do something very simple, but I can't manage to. Here is my code globally:

var Test = class Test 
{
    constructor(var_x, var_y) {
    this.x = var_x;
    this.y = var_y;

} };

and

var y = {Value: 2};
var test1 = new Test(0, y.Value);
y.Value +=2;
console.log(test1);

my problem is that I display (0,2), and as I incremented y.Value, I expected (0,4). What did I miss ? Thank you!

Letchi
  • 3
  • 2
  • 1
    In JS primitives are always passed by value. Pass an object or array if you want to maintain a reference. – Ori Drori Apr 01 '18 at 18:43
  • Thank you! Sorry I'm a beginner and I don't understand your comment :( – Letchi Apr 01 '18 at 18:51
  • Primitives such as words and numbers are only passed by value (a copy is created). Objects and arrays are passed by reference (a pointer). If you change a property of an object, all reference to the object will reflect the change, because they point to the same object. – Ori Drori Apr 01 '18 at 18:55

1 Answers1

0

This behaviour can be explained because you are passing a value to the constructor, not a reference:

var Test = class Test 
{
    constructor(var_x, var_y) {
        this.x = var_x;
        this.y = var_y;
    } 
};

var y = {Value: 2};
var test1 = new Test(0, y.Value);
console.log(test1)
test1.y +=2;  // <-- NOTE
console.log(test1);

You could also do something like this (which I'd not recommend due to a bad software pattern):

var y = {Value: 2};

var Test = class Test 
{
    constructor(var_x) {
        this.x = var_x;
        this.y = y;   // <-- NOTE
    } 
};


var test1 = new Test(0, y.Value);
console.log(test1)
y.Value +=2;
console.log(test1);

In this example the Test.y value is a reference to another variable (var y)

messerbill
  • 5,499
  • 1
  • 27
  • 38
  • Thank you! What I am trying to do it to modify test1.y value by modifying y value, I want to declare test1 and not modify it after. – Letchi Apr 01 '18 at 18:55
  • @Letchi yes this is why i added the second example (where `test1` is **not** modified directly afterwards) – messerbill Apr 01 '18 at 18:56
  • Ok thx. It's possible to call a one argument constructor with two arguments ? – Letchi Apr 01 '18 at 19:01
  • @Letchi I guess this can help you: https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – messerbill Apr 01 '18 at 19:02