这是一个JavaScript模式吗?

时间:2014-07-15 12:35:13

标签: javascript design-patterns

这是一种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};

3 个答案:

答案 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