这是一种JavaScript模式吗?以下代码更改了test.get_context()对象:
var test = {},
value = {};
test.get_context = function(val) {
return function() {
return val;
}
}(value);
var context = test.get_context();
context["test"] = 123;
//context = { "test": 123};
console.log(test.get_context());
但以下内容并没有改变它:
var test = {},
value = {};
test.get_context = function(val) {
return function() {
return val;
}
}(value);
var context = test.get_context();
//context["test"] = 123;
context = { "test": 123};
console.log(test.get_context());
在这种情况下,
之间有什么区别context["test"] = 123;
和
context = { "test": 123};
答案 0 :(得分:0)
context["test"]
将context.test
设置为123
。
context = { "test" : 123}
用test
= 123
更新值和替换变量之间的区别。
您的第一个版本更新了对象,而第二个版本会覆盖它。
答案 1 :(得分:0)
在这种情况下,
之间有什么区别context [“test”] = 123;
和
context = {“test”:123};
第一个设置对象的属性,第二个用新的替换对象
答案 2 :(得分:0)
第一个是数组,它是动态访问的。例如
var foo = 'index1';
var context = [];
var context1 = {'index1':'test'};
context['index1'] = 'test';
console.log(context[foo]) // it returns test
如果我输入console.log(context1.foo) // it return undefined error
可以将值评估为数组格式,例如console.log(context1[foo]) // it return test