【发布时间】:2015-10-05 14:44:05
【问题描述】:
我正在尝试像这样更改对象的属性:
secondFunction = function()
{
var bla = {
a:1, //properties
};
bla.localFunction = function(){
a = 2; //can he read and modify this property?
}
return bla; //return back object
}
firstFunction = function()
{
var testing = secondFunction(); //now testing is the object.
testing.localFunction(); //this is supposed to call localFunction and change the "a" property to 2
console.log(testing.a); //displays 1, not 2 as I thought it would
}
firstFunction();
我可能是错的(因为我是 javascript 新手),但是属性对于整个对象是全局的,并且由于 localFunction 是对象的一部分,我认为它应该能够读取属性“a”并对其进行修改到 2. 我哪里错了?
【问题讨论】:
-
您正在寻找
this关键字。this不是块作用域!尝试使用this.a = 2。本质上,不,块中声明的变量不像“局部全局变量”——this关键字将包含它的“范围”。这有点简化,但请阅读:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
我在这里看不到任何继承...另外,IIRC,
a不会是secondFunction的变量,而是一个全局变量,即console.log('a')应该打印一些东西. -
@CedricReichenbach
a在这里不是全局的,bla是它的父级,bla 是函数返回的,因此分配给全局的testingvar,因此只有testing是直接的全球的。a是return值secondFunction的变量。 -
ainsidebla.localFunction是全局的。a里面bla不是。 -
啊,我没看到
bla里面的a:1。
标签: javascript inheritance var