在 JavaScript 中循环访问 "function" 对象



我有一个项目,我想将一个"函数"对象(与JSON对象——一个对象文字)与一个现有对象合并。我想得到"公开可见"的财产。然而,当我在循环中执行时,它们不会出现。它们不会触发内部的CCD_ 1。我怎样才能拿到它们?

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

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

一旦var foo = new obj();,您将看到属性(在foo上)。

或者,移动设置属性的代码,使其位于函数之外。

您可以使其自动执行:

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

最新更新