2011-09-20 266 views
1

我有像從javascript中的對象方法訪問對象屬性

這樣的
var foo = function(arg){ 
    var something = { 
    myPropVal: "the code", 
    myMethodProp: function(bla) { 
     // do stuff with mypropval here 
     alert(this) // => DOMWindow 
    } 
    } 
} 

這可能嗎?我可以在給定

的myMethodProp中訪問myPropVal的內容
+0

警報(this.myPropVal)的作品。 – dhinesh

回答

3

確保您可以

var foo = function(arg){ 
    var something = { 
    myPropVal: "the code", 
    myMethodProp: function(bla) { 
     // do stuff with mypropval here 
     alert(this) // => DOMWindow 
     alert(this.myPropVal); 
    } 
    } 

    alert(something.myMethodProp()); 
} 
foo(); 
+0

所以實際上'this'不是DOMWindow。 – pimvdb

+1

什麼'this'取決於函數如何被調用的上下文。所以你明確地使用'something'可能更安全。 –

2

您可能必須將其引用爲something.myPropVal