闭包中的本地变量从外部更改.这是一个javascript错误,或者我做错了什么

Local variable in closure changing from outside of it.This is a javascript bug or I am doing something wrong?

本文关键字:javascript 错误 一个 或者 什么 错了 变量 从外部 闭包      更新时间:2024-02-23

我使用闭包是为了隐私。我不明白为什么以及如何从闭包之外更改局部变量。

我写了一个脚本来向你们解释这个问题。

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函数的编写方式是,它总是直接更新作为第一个参数传递的对象。因此,为了确保不更改该对象,只需传入一个新创建的对象作为第一个参数。