繁体   English   中英

循环浏览javascript中的“函数”对象

[英]Looping through a “function” object in javascript

我有一个项目,我想将一个“功能”对象(与JSON对象-对象文字相反)与现有对象合并。 我想获取“公开可见”属性。 但是,当我进行for in循环时,它们不显示。 它们不会触发内部的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
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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