with关键字在javascript中是不是很糟糕?

isl*_*205 2 javascript

可能重复:
JavaScript的"with"语句是否有合法用途?

在"JavaScript the Good Parts"中,with被认为是javascript的一个不好的部分,但请看这个片段:

var foo={foof:function(){console.log(this)}}
var fuu={fuuf:function(){console.log(this)}}
with(foo){
     console.log(this);
 with(fuu){
     console.log(this);
     foof();
     fuuf();
 }
}
Run Code Online (Sandbox Code Playgroud)

是否with真的如此糟糕做法?with有时可以提供乐趣或优势,谁可以举个例子?

Way*_*ett 5

这很方便,但它仍然有一个根本问题,可以让你快速陷入困境.考虑一下:

var foo={foof:function(){console.log(this)}}
var fuu={fuuf:function(){console.log(this)}}
with(foo){
     console.log(this);
 with(fuu){
     console.log(this);
     foof();
     fuuf();
 }
 myProp = "blah";
}
Run Code Online (Sandbox Code Playgroud)

现在我们分配到什么时发生了myProp什么?

很难说.

如果foo包含名为的属性myProp,则其值现在为"blah".但如果没有,那么我们只是分配"blah"myProp全局对象(可能window).在这个简单的例子中很容易分辨出这是怎么回事,但如果foo早先定义了1000行呢?或者在另一个文件中?那不容易.

更多信息和您问题的实际答案:

JavaScript的"with"语句是否有合法用途?

和这里:

http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/