简体   繁体   中英

Looping through a “function” object in javascript

i have this project where i would like to merge a "function" object (in contrast to the JSON object - an object literal) with an existing object. i would want to get the "publicly visible" properties. however, when i do a for in loop, they don't show up. they don't trigger the console.log() inside. how do i get them?

//obj passed to extend() by external caller
//this is what obj it looked like when i console.log()'ed it
obj = function() {

    //skip these private ones
    var imPrivate = 'i should not be included';
    function imGetter() {}

    //i want these guys below:
    this.getter = imGetter;
    this.imPublic = "i should be included";

}

function extend(obj){
    console.log('i can see here');

    for (var key in obj) {
        console.log('you cannot see here');
    }​

    //...more of our code here
}

Those properties don't exist until you call the function.

Once you var foo = new obj(); then you will see the properties (on foo ).

Alternatively, move the code that sets the properties so it is outside the function .

you could make it self execute:

var obj={};
(function(ns) { //skip these private ones   
    var imPrivate = 'i should not be included';

    function imGetter() {};
    //i want these guys below:  
    ns.getter = imGetter;
    ns.imPublic = "i should be included";
})(obj)
console.log('i can see here');
for (var key in obj) {
    console.log('you cannot see here '+key+" holds:"+obj[key]);
}

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