2012-05-23 51 views
0

我對JavaScript很新,所以也許這是一個愚蠢的錯誤。 我創建像follwing對象:JavaScript傳遞對象作爲函數參數

function objA(){ 
    this.prop1; 
    this.prop2; 
    this.prop3; 
    this.func1=function(){ 
     alert('func1'); 
    } 
    this.func2=function(){ 
     alert('func2'); 
    } 
} 

我現在,我要傳遞的對象的函數:

var foo=new objA; 

function test(foo){....} 

的問題是,當我叫試驗(+),我得到的在objA(objA.func1和objA.func2)中執行函數。 我只想獲得objA的屬性值。 我要使用其他功能和數組,objA的屬性填充數組,然後將數組:

var arrayA={} 

function fillArray(data){ 
    arrayA.prop1=data.prop1; 
    arrayA.prop2=data.prop2; 
    arrayA.prop3=data.prop3; 
} 

function test(arrayA){....} 

是它唯一的出路還是我做錯了什麼?

+3

是,你的測試功能是錯誤的,當它做你不想要的東西。你可以發佈它,這似乎是至關重要的問題? – Bergi

+0

同意......沒有看到test()的代碼,所以不可能說出發生了什麼。 – Pointy

+0

正如你可以看到那裏,它正常工作http://jsfiddle.net/GhNmK/1/。所以你的測試函數的原因如上所述Bergi –

回答

2

函數對象的屬性(它們是一等值),因此它們在for (var propName in myObj)循環中與其他任何屬性一樣出現。您可以通過避免進一步檢查他們:

for (var prop in myObj){ 
    if (!myObj.hasOwnProperty(prop)) continue; // Skip inherited properties 
    var val = myObj[prop]; 
    if (typeof val === 'function')) continue; // Skip functions 

    // Must be my own, non-function property 
} 

另外,在現代瀏覽器可以讓特定的屬性(如您的函數)不可枚舉,所以他們不會在for ... in循環顯示:

function objA(){ 
    this.prop1 = 42; 
    Object.defineProperty(this,'func1',{ 
    value:function(){ 
    ... 
    } 
    }); 
} 

更多關於此,請參閱Object.definePropertyObject.defineProperties的文檔。

最後,如果你不需要定義功能closures您可以在對象的原型在這種情況下hasOwnProperty測試將導致他們被跳過定義它們:

function objA(){ 
    this.prop1 = 42; 
} 
objA.prototype.func1 = function(){ 
    // operate on the object generically 
}; 

var a = new objA; 
"func1" in a;    // true 
a.hasOwnProperty("func1"); // false 
+0

謝謝你的解釋。我會嘗試原型定義方法。我選擇關閉,因爲它在我看來更加乾淨。 – DarioD

相關問題