今天我在w3resource上看过代码,我在想它的作用:
var var_name = 'abcd';
var n = 120;
this[var_name] = n;
console.log(this[var_name]);
// the OUTPUT : 120
// This line was added to this example.
console.log(abcd);

首先我认为要更改变量值但是当我在控制台中输入var_name
来获取它给我的值时,#abcd'。实际上这对我来说很困惑。
答案 0 :(得分:-1)
嘿,我添加了评论。希望这有助于您理解代码
var var_name = 'abcd'; //creates a new variable with the name var_name and the
value 'abcd'
var n = 120; //creates a new variable with the name n and the value 120
this[var_name] = n; //add a new property with the value of var_name (abcd) to this and the value of n (120)
答案 1 :(得分:-1)
在JavaScript中this
总是指我们正在执行的函数的“所有者”,或者更确切地说,指向函数是其方法的对象。但由于在代码中全局使用this
,因此它与文档级别相关。所以,
var var_name = 'abcd';
创建值为var_name
的变量名abcd
。这通常用于创建变量。
但是,
var n = 120;
this[var_name] = n;
制作对象时可以访问。当我们希望属性与对象的生命存在时,我们将属性添加到this
。我们将var
用于局部变量。
因此,this[var_name]
和var_name
会分开处理。