简体   繁体   中英

Issue finding all variables in an Object

I have an Object called Button_Objs , its purpose is to hold all my Button Objects. I made a function in my Button_Objs which iterates through each of its variables. Here is where the issue is, I have a if statement that says: if (i typeof Button){} . I do this so it only selects the Button Objects that are stored.

Here is the JSFiddle of this: http://jsfiddle.net/MichaelMitchell/vcZTR/15/

var Button_Objs = function() {
    this.getButtons = function() {
        var i;
        for (i in this) {
            if (type of i == Button) { //PROBLEM, also does not work with instanceof.

                document.getElementById('console').innerHTML += ( "button: " + i  + "<br />");

            }
        }
    };
};

I also tried instanceof , but alas it will not work :(

i typeof Button is invalid syntax and type of i == Button as well.

When you use a for...in loop to iterate over an object, the loop variable will hold the name of the property, not the value. You can use the name to get the value:

if(this[i] instanceof Button)

Read more about the for...in loop (I recommend to have a look at MDN to learn about JS basics).


Apart from this, I don't see why you need a constructor function to create a container for your buttons. You could just use a plain object:

var buttons = {};

// somewhere
buttons['button' + i] = new Button(...);

and then again use the for...in loop to iterate over the object.

And if you don't actually need the names (they just seem to be some sort of enumeration), why don't you use an array?

var buttons = [];

// somewhere
buttons.push(new Button(...));

and then use a for loop to iterate over all buttons. You would not even have to test for their type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM