with()语句中的函数没有接收定义的对象
Function inside a with() statement doesn't receive the defined object
当我在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);
}())
相关文章:
- 在Javascript服务器/客户端中共享对象定义
- 高级布线和单个对象定义
- Javascript 对象定义
- 是否可以为数组中的每个对象定义事件侦听器
- 如何在多个文件中拆分 JavaScript 对象定义
- 将对象定义为仅包含特定类型的元素
- 如何在 javascript 中为 dom 对象定义函数
- 您可以在 JavaScript 中的私有方法中访问对象定义的属性吗?
- 在 ecma-script-6 中将对象定义为常量
- 在 JavaScript 中使用对象定义局部变量
- 如何在 JS 对象定义中引用字段
- 属性的对象定义属性设置器
- Three.js对象定义未定义
- 对象定义有两种方式-有什么区别
- JavaScript-如何在对象定义中定义属性
- 对象定义中的方括号表示法
- 仅为{..}对象定义原型
- 在对象定义中的javascript Repeating属性中(在大括号内).这是个错误吗
- 特殊的JavaScript结构:对象定义中的对象类型变量
- 在javascript对象定义中连接字符串