从对象创建的 Javascript 对象总是引用最后一个元素
Javascript object created from objectss always references last element
这是一个
奇怪的问题。鉴于下面的 javascript,我希望 newFunctions 对象包含包装原始对象的函数,但它只运行循环中发生的最后一个操作。var actionToCall 不应该复制对当前操作当前正在查看的内容的引用,并且在循环迭代时不更改吗?我在这里被难住了。
var typeArray = {
type1: {
function1: function() {
console.log("this is function 1");
},
function2: function() {
console.log("this is function 2");
}
},
type2: {
somefunction: function() {
console.log("this is some function")
}
},
type3: {
blah: function() {
return;
},
moreBlah: function(something) {
console.log(something);
},
evenMore: function() {
console.log("I'm last!");
}
}
},
index,
typeIndex,
currentType,
actionIndex,
currentAction,
newFunctions = {};
for(typeIndex in typeArray) {
currentType = typeArray[typeIndex];
for(actionIndex in currentType) {
currentAction = currentType[actionIndex];
console.log(currentAction.toString());
newFunctions[actionIndex] = function() {
var actionToCall = currentAction;
console.log("about to run action");
actionToCall.call(this);
console.log("action has been called");
}
}
}
console.log(newFunctions);
for(index in newFunctions) {
(newFunctions[index])();
}
这是因为 actionToCall 被分配给了当前操作。
由于 currentAction 是全局的,因此它的值随着循环迭代而不断变化。
当循环结束时,currentAction被分配给evenMore。
下面是使用自执行函数来诱导范围的修复。
var typeArray = {
type1: {
function1: function() {
console.log("this is function 1");
},
function2: function() {
console.log("this is function 2");
}
},
type2: {
somefunction: function() {
console.log("this is some function")
}
},
type3: {
blah: function() {
return;
},
moreBlah: function(something) {
console.log(something);
},
evenMore: function() {
console.log("I'm last!");
}
}
},
index,
typeIndex,
currentType,
actionIndex,
currentAction,
newFunctions = {};
for(typeIndex in typeArray) {
currentType = typeArray[typeIndex];
for(actionIndex in currentType) {
currentAction = currentType[actionIndex];
console.log(currentAction.toString());
//induce scope here so actionToCall keeps the current value of currentAction.
(function(){
var actionToCall = currentAction;
newFunctions[actionIndex] = function() {
console.log("about to run action");
actionToCall.call(this);
console.log("action has been called");
}
})();
}
}
console.log(newFunctions);
for(index in newFunctions) {
(newFunctions[index])();
}
相关文章:
- 如何使用object.assign()从其他对象引用基本对象属性
- 返回 JavaScript 类值而不是对象引用
- Facebook:当发布期望对象引用时显示打开的图形对话框
- Javascript-如何从字符串/对象引用回调
- 将其用于对象引用
- 如何将对象引用传递到 mootools 中另一个对象的构造函数中
- Javascript:将类/对象引用设置为 NULL,内存中的子对象/类会发生什么
- 在 Jquery 中,我可以存储对象引用并在以后使用它吗?
- 将对象函数传递给请求动画帧时丢失对象引用
- JavaScript ecma6中的对象引用
- 在JSON中存储对象引用
- 为什么可以在内部函数成员中访问对象引用,而不能在内部属性成员中访问
- 对象引用的隐式传递是如何工作的
- 按对象的 ID 删除对选定对象的对象引用
- 在调用的函数中使用对象引用(this)
- 如何在testcomplete+js中获取对象引用
- 在Angularjs服务中为返回对象引用的http请求提供的数据构建简单的缓存
- JavaScript对象引用
- 对象引用未设置为行中的对象的实例,如果 (!string.IsNullOrEmpty(tdcd.文本)&&
- 如何在使用声明式 Dojo 时获取对象引用