with()语句中的函数没有接收定义的对象

Function inside a with() statement doesn't receive the defined object

本文关键字:对象 定义 函数 语句 with      更新时间:2023-09-26

当我在with()语句中定义和调用Function时,该函数不接收with()中定义的对象。有办法解决我的问题吗?

例如,下面的代码不能工作:

var testObj = { testStr: "Hello World!" };
with(testObj) {
  function testFunc(){
     alert(testStr);
  }
  testFunc();
}

这是一个函数声明。

函数一开始就不应该在语句块中声明。

一个表达式将工作:

var testObj = { testStr: "Hello World!" };
with(testObj) {
  var testFunc  = function(){
     alert(testStr);
  }
  testFunc();
}

使用函数表达式:

var testObj = { testStr: "Hello World!" };
with(testObj) {
  var testFunc = function(){
     alert(testStr);
  };
  testFunc();
}

函数声明被提升了,所以这不起作用。

看起来像是指向testFunc(),而不是testObj。

var testObj = { testStr: "Hello World!" };
with(testObj) {
    function testFunc(){
        alert(this == testObj);
    }
    testFunc();
}

不要使用with (1):

var testObj = { testStr: "Hello World!" };
(function() {
  alert(testObj.testStr);
}())