为什么javascript可以持久化外部函数中发生的局部变量重新分配而不必捕获返回值?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了为什么javascript可以持久化外部函数中发生的局部变量重新分配而不必捕获返回值?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2453字,纯文字阅读大概需要4分钟。
内容图文
![为什么javascript可以持久化外部函数中发生的局部变量重新分配而不必捕获返回值?](/upload/InfoBanner/zyjiaocheng/683/dbd9fe9695f342688abe3592eddf84a4.jpg)
我是一个ruby程序员,所以如果您有这样的事情,我通常来自哪里:
def addone(x)
x+1
end
def ruby_assignment_behavior(x)
addone(x)
puts "x equals " + x
end
运行最后一个方法将导致以下结果:
ruby_assignment_behavior(1)
#=> "x equals 1"
我认为在javascript中,与此等效的东西将返回x等于2.
在研究了这段代码(获取用户gps坐标)后,我发现了这种独特的javascript质量(相对于ruby)
var currPosition;
navigator.geolocation.getCurrentPosition(function(position) {
updatePosition(position);
$("#lat").html(position.coords.latitude;);
$("#lng").html(position.coords.longitude);
};
function updatePosition(position) {
currPosition = position;
}
为什么在getCurrentPosition函数中,即使position是闭包()内的局部变量,也会使用updatePosition()的返回值来更新position变量?
也:
我很好奇,在javascript代码示例中,是否有必要在getCurrentPosition之外使用该updatePosition函数,如果需要,为什么会这样呢?在最外部作用域中定义的currPosition变量是否以某种方式带有重新分配的位置值?
解决方法:
这两段代码非常不同.在Ruby代码中,您正在更改变量值.由于变量是局部变量,因此请正确声明,更改不会反映在范围之外.
在您的JavaScript代码中,您正在更改变量所指向的对象的内部状态.变量本身不会更改.
在这方面,Ruby和JavaScript的行为相同.
var a = { count: 0 };
function increment(x) {
x.count++; // variable changed, changing referenced object state
}
increment(a);
console.log(a.count);
// => 1
相当于
a = { count: 0 }
def increment(x)
x[:count] += 1 # variable changed, changing referenced object state
end
increment(a)
puts a[:count]
# => 1
而
var b = { count: 0 };
function increment(x) {
x = { count: x.count + 1 }; // changing variable's reference
}
increment(b);
console.log(b.count);
// => 0
相当于
b = { count: 0 }
def increment(x)
x = { count: x[:count] + 1 } # changing variable's reference
end
increment(b)
puts b[:count]
# => 0
函数外部的var currPosition声明变量currPosition的作用域比该函数宽,这有点像,但不完全像在Ruby中使用$currPosition一样.这允许函数将值分配给一个可见的变量,并将其覆盖:
var c = 0; // outer scope
function update() {
c = 1;
}
update();
console.log(c);
// 1
但
function update() {
var d = 0; // inner scope
d = 1;
}
update();
console.log(d);
// undefined
在Ruby中,不允许变量跳转这样的函数(方法)范围,但是您可以使用@a,@@ a或$a来访问外部范围(实例,类或全局):
def update
c = 1 # local scope
end
update
puts c
# => Error
但
@d = nil # instance scope
def update
@d = 1
end
update
puts @d
# => 1
但是,Ruby中的块与JavaScript中的函数具有类似的范围效应:
e = nil # outer scope
1.times do
e = 1
end
e
# => 1
但
1.times do
f = 1 # inner scope
end
f
# => Error
内容总结
以上是互联网集市为您收集整理的为什么javascript可以持久化外部函数中发生的局部变量重新分配而不必捕获返回值?全部内容,希望文章能够帮你解决为什么javascript可以持久化外部函数中发生的局部变量重新分配而不必捕获返回值?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。