在JavaScript中,链接分配好吗? [英] In JavaScript, is chained assignment okay?
问题描述
对JS或其语法不是新手,但有时候,语言的语义有时让我感到难过。在今天的工作中,一位同事提到了这一点:
var a = b = [];
与
<$ p $不同p>
var a = [],b = [];
或
var a = []; var b = [];
因为第一个版本实际上将对空数组的引用分配给a和b。我不能完全接受这一点,但我不确定。你们都在想什么?
是的,它们不一样。 var a = b = []
相当于
var a;
b = [];
a = b;
不仅 a
和 b
获得相同的值(对同一个空数组的引用), b
根本没有声明。在ECMAScript 5及更高版本的严格模式中,这将抛出 ReferenceError
;否则,除非范围内已有变量 b
,否则 b
将自动创建为全局对象的属性,类似于全局变量,无论代码在哪里,甚至在函数内部。哪个不好。
你可以很容易地看到这个:
(function(){
var a = b = [];
})();
window.console.log(b); //显示[]
Am not new to JS or its syntax, but sometimes, the semantics of the language has me stumped at times. At work today, a colleague mentioned this:
var a = b = [];
is not the same as
var a = [], b = [];
or
var a = []; var b = [];
since the first version actually assigns the reference to an empty array to a and b. I couldn't quite accept this as true, but I'm not sure. What do you all think?
Yes, they're not the same. var a = b = []
is equivalent to
var a;
b = [];
a = b;
Not only do both a
and b
get assigned the same value (a reference to the same empty array), b
is not declared at all. In strict mode in ECMAScript 5 and later, this will throw a ReferenceError
; otherwise, unless there is already a variable b
in scope, b
is silently created as a property of the global object and acts similarly to a global variable, wherever the code is, even inside a function. Which is not good.
You can see this quite easily:
(function() {
var a = b = [];
})();
window.console.log(b); // Shows []
这篇关于在JavaScript中,链接分配好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!