我正在学习 Javascript,但我不明白为什么这段代码有效:
function getObj()
{
var objAddress =
{
address: "Client Address",
getAddress: function() {
return this.address;
},
setAddress: function(newAddress)
{
this.address = newAddress;
}
};
var objClient =
{
name: "Client name",
getAddress: function()
{
return objAddress.getAddress();
},
setAddress: function(newAddress) {
objAddress.setAddress(newAddress);
}
};
return objClient;
}
gObj = getObj();
console.log(gObj.getAddress()); // Will print "Client Address"
gObj.setAddress("xpto");
console.log(gObj.getAddress()); // Will print "xpto"
我认为它不起作用,因为getAddress()
调用了离开函数后不应该存在的对象的另一个方法。但是,由于这是有效的,我认为即使在退出该功能后该对象objAddress
仍然存在。getObj
功能之外,怎么可能gObj.getAddress()
工作?