2011-09-20 177 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