How to make two references to one object

Viewed 92

I'm running the following code:

function Status(type) {
  this.type = type;
}


var race = new Status('race');
var status = race;
console.log(status);
console.log(race);

and the result is

[object Object]
Status {type: "race"}

Why are status and race giving different results? The '==' comparison returns true, whereas the '===' comparison returns false; how can I make status and race point to the same object?

5 Answers

The value of status is actually a string while the value of race is an object.

If you use the typeof operator on both variables, you will discover this.

I think this is happening because status is reserved for window.status but I could be wrong.

You seem to be running into a conflict with window.status.

Change the variable name or put things into a non-global scope.

It works fine for me and returns the same object in both the instance.

See my jsfiddle

Are you trying to run this in a browser console? If yes, it might be causing a conflict with the window object in global scope.

Your code is correct the only problem is there are some issues as status is already a global variable in JS(window object), this should work fine.

function Status(type) {
  this.type = type;
}


var race = new Status('race');
var status2 = race;
console.log(status2);
console.log(race);

See this for more information https://developer.mozilla.org/en-US/docs/Web/API/Window/status , whenever you assign any value to status it automatically converts that value to string, that was the reason your condition why you were seeing two different object one was string and one was object.

You are use a the same name that you use for Object and for var, you only need change the name for the var that you use Something like:

function Status(type) {
      this.type = type;
    }

var race = new Status('race');
var getStatus = race;
console.log(getStatus);
console.log(race);

Result: { "type": "race" } { "type": "race" }

Related