闭包中的本地变量从外部更改.这是一个javascript错误,或者我做错了什么
Local variable in closure changing from outside of it.This is a javascript bug or I am doing something wrong?
我使用闭包是为了隐私。我不明白为什么以及如何从闭包之外更改局部变量。
我写了一个脚本来向你们解释这个问题。
var MyAjax=(function(){
//Create a local variable for privacy
var _opts={
cache:true
}
,getDefaultOptions=function(){
return _opts
};
//return only getDefaultOptions function
return {
getDefaultOptions:getDefaultOptions
}
})()
//I am merging new ajax options with default options.
var defaults=MyAjax.getDefaultOptions();
var reqOptions= $.extend(defaults,{cache:false});
// I am getting expected result
console.log("extended var",reqOptions) //{cache:false}
// I am getting non expected result
// I should get {cache:true} but I am getting { cache:false }
console.log("defaults",MyAjax.getDefaultOptions()) //{cache:false}
为什么会发生这种情况以及如何发生?
$.extend()
函数修改第一个参数。如果你不想这样,就这样做:
var reqOptions = $.extend({}, defaults, {cache: false});
详细说明:将对对象的引用作为第一个参数进行传递。即使它是该闭包的私有变量,getter函数也返回了对它的引用,因此它是"可见的"。jQuery函数的编写方式是,它总是直接更新作为第一个参数传递的对象。因此,为了确保不更改该对象,只需传入一个新创建的对象作为第一个参数。
相关文章:
- JavaScript错误:Microsoft JScript运行时错误:应为对象
- 将字符串拆分为数组时出现JavaScript错误
- 处理JSON字符串会导致JavaScript错误
- 使用AJAX在剑道网格中分组时出现Javascript错误
- Ajax对web URL的调用导致javascript错误
- 为什么当我尝试在Ionic中使用列表时会出现此JavaScript错误
- 可以't解决Javascript错误
- django出现神秘的javascript错误
- JavaScript错误无效的限定符
- 使用主题运行时portlet liferay时出现Javascript错误
- 绑定函数时在IE7中未实现Javascript错误
- Javascript错误:未捕获引用错误:未定义编辑
- eventListener出现JavaScript错误
- sharepoint站点的internet explorer中出现Javascript错误
- LoadControl HttpCompileException自定义服务器控件JavaScript错误
- 销毁Bootstrap popover时出现Javascript错误
- 无法加载Javascript错误XMLHttpRequest
- 使用JSON.parse时出现无效字符javascript错误
- 修复Javascript错误
- 模板字符串上的netbeans javascript错误(backticks)