簡體   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