通过javascript中的“函数”对象循环

时间:2012-02-14 16:48:03

标签: javascript object loops

我有这个项目,我想合并一个"功能"具有现有对象的对象(与JSON对象 - 对象文字形成对比)。我希望公开显示""属性。但是,当我在循环中执行时,它们不会显示出来。他们不会触发内部的console.log()。我怎么得到它们?

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

2 个答案:

答案 0 :(得分:4)

在调用函数之前,这些属性不存在。

var foo = new obj();后,您会看到the properties(在foo上)。

或者,移动设置属性的代码,使其为outside the function

答案 1 :(得分:0)

你可以自己执行:

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]);
}