我想知道如何使用功能訪問「南」電子可變的JavaScript物件,像這樣:Javascript變量作用域。如何從內部對象函數訪問對象變量?
function myObj() {
this.vars = {
name: 'bob',
age: '42'
}
this.functions = {
sayName: function() {
alert(this.vars.name);
}
}
}
var obj = new myObj();
obj.functions.sayName();
缺少什麼我在這裏?
我能得到的名稱VAR如果我通過到自身的引用,如:
function myObj() {
this.vars = {
name: 'bob',
age: '42'
}
this.functions = {
sayName: function(name) {
alert(name);
}
}
}
var obj = new myObj();
obj.functions.sayName(obj.vars.name);
,但似乎有點多餘...想法?
真棒的答案。我確實需要保持外部組件可訪問的變量,因此添加this.vars =是關鍵。謝謝! – 2012-04-15 01:15:11