Gnago Gnago - 17 days ago 5
HTML Question

Finding the object's name using the constructor's argument's values

So using the following part of my code, I've been trying to find the object's name ("object's name" refers to foo, bar, baz, and jar below. Sorry if that's the improper term, couldn't find any examples like this one on the web that termed them) using the values of the constructed function. To give an example:

function myFunction(){
foo = new component(50, 50, "first", "red");
bar = new component(50, 100, "sec", "red");
baz = new component(0, 50, "third", "blue");
jar = new component(0, 100, "fourth", "blue");
}
function component(x, y, id, color){
this.x = x;
this.y = y;
this.id = id;
this.color = color;
}


So if I have the value of both x and y, 50 and 100 respectively, what method would I use to make it so that the program will recognize that the constructor with these values is bar? If doing this using two values is impossible, using only one value is totally fine since I can always just combine the two into one. So far the best thing I've been able to come up with that somehwhat worked was that "foo instanceof component" is true, so maybe there's some method that I've yet to find that's basically the opposite of instance of? Thank you in advance.

Answer

In your code foo, bar, baz and jar are variables, not constructors. These variables are pointing to objects that were created using the component function as the constructor.

It sounds like what you're trying to do is to find the object that was created using the specific values for x and y. One way to do that would be to have a lookup table where the keys are the combination of x and y, and the values are the objects:

var objects = {};
function component(x, y, id, color) {
    this.x = x;
    this.y = y;
    this.id = id;
    this.color = color;

    // Insert the current object into the lookup table
    objects[x + '_' + y] = this;
}

// Retreive an object from the lookup table
function findObject(x, y) {
    return objects[x + '_' + y];
}

One problem with this approach is that if you create two objects with the same x and y values, only the last one will be stored in the lookup table. You could solve that by storing an array of objects for each key instead.

Comments