2012-02-14 56 views
0

我有这个项目,我想合并“功能”对象循环(与JSON对象 - 一个对象文本)与现有对象。我想获得“公开可见”的属性。然而,当我在环路做,他们不露面。他们不触发console.log()内。我如何得到它们?通过“功能”对象在JavaScript

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

你要么需要运行功能或用'new'运营商创建它的一个实例之前,任何这些属性的设定。 – 2012-02-14 16:50:53

+0

实际上,这里'是obj'只是为了显示我传递给环路(如图控制台)。循环是我们命名为'extend',函数,它是无关的问题:) – Joseph 2012-02-14 16:54:14

回答

4

这些属性不存在,直到你调用该函数。

一旦你var foo = new obj();然后你会看到the properties(在foo)。

或者,动议设置属性所以它是outside the function的代码。

+0

完美的一部分。现在我知道一个未调用的对象在控制台中的样子! (并在需要调用时调用它)。 – Joseph 2012-02-14 17:21:00

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