Edylk
Edylk

Reputation: 55

How to make two references to one object

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?

Upvotes: 3

Views: 103

Answers (5)

chackerian
chackerian

Reputation: 1401

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.

Upvotes: 2

dCandamil
dCandamil

Reputation: 3

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" }

Upvotes: 0

Deepak Sharma
Deepak Sharma

Reputation: 1901

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.

Upvotes: 0

TeaCoder
TeaCoder

Reputation: 1977

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.

Upvotes: 1

Thilo
Thilo

Reputation: 262534

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

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

Upvotes: 1

Related Questions