为什么此JavaScript属性返回空字符串,而JavaScript函数却可以正常工作? [英] Why this JavaScript property returns empty string, while JavaScript function works fine?
问题描述
考虑以下简单的JavaScript模块模式:
var human =(function(){var _name ='';返回 {名称:_name,setName:函数(名称){_name =名称;}}})();human.setName('somebody');警报(human.name);//显示一个空字符串人=(函数(){var _name ='';返回 {名称:function(){返回_name;},setName:函数(名称){_name =名称;}}})();human.setName('somebody');警报(human.name());//显示某人"
为什么第二个闭包能正常工作,而第一个闭包却不工作?参见示例此处.
另请参见此小提琴,它证明了可以使用简单的属性来代替getter函数.
在Java语言中
- 字符串和原始类型(布尔值和数字)通过值传递
- 对象,数组和函数通过引用传递
由于名称是字符串,所以 name:_name
将存储 _name
的当前值,而不是对 _name
的引用.
setName
仅会修改 _name
.
getName
将访问保存当前值的 _name
.
.name
将访问在初始化期间设置的复制值( name:_name
).
另请参见 SO:按引用而不是按值的Java脚本 >
Consider this simple JavaScript module pattern:
var human = (function () {
var _name = '';
return {
name: _name,
setName: function (name) {
_name = name;
}
}
})();
human.setName('somebody');
alert(human.name); // shows an empty string
human = (function () {
var _name = '';
return {
name: function() {
return _name;
},
setName: function (name) {
_name = name;
}
}
})();
human.setName('somebody');
alert(human.name()); // shows 'somebody'
Why the second closure works fine, while the first closure is not working? See example here.
Please also see this fiddle, which proves that simple properties can be used instead of getter functions.
In Javascript
- Strings and primitive types (boolean and numeric) are passed by value
- Objects, arrays, and functions are passed by reference
As name is a string name: _name
will store the current value of _name
and not the reference to _name
.
setName
in your example will modify only _name
.
getName
will access _name
which holds the current value.
.name
will access the copied value which was set during the initialisation (name: _name
).
See also SO: Javascript by reference vs. by value
这篇关于为什么此JavaScript属性返回空字符串,而JavaScript函数却可以正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!