下面的with
语句指定[Math](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math "JavaScript/Reference/Global_Objects/Math")
对象作为默认对象。with
语句里面的变量,分別指向Math
对象的PI
、[cos](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos "JavaScript/Reference/Global_Objects/Math/cos")和``[sin](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin "JavaScript/Reference/Global_Objects/Math/sin")
函数,不用在前面添加命名空间。后续所有引用都指向Math
对象。
如下:with不改变this指向!
var a, x, y;
var r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
with({num:11,say:function(){alert(22)},this:33}){
console.log(num); // 11
console.log(say()); // 22
console.log(this) ; // Window
}
严格模式和 new Function
// 严格模式和 new Function
// 严格模式作用范围
// new Function 因为Function === window.Function
(function(){
'use strict' // 只能在作用域第一句
console.log('this11:',this);
(function (){
new Function('console.log("this33:",this)').bind({name:"haha"})()
})();
})();
console.log('this22:',this)
严格模式和with
在 ECMAScript 5 严格模式中该标签已被禁止
。推荐的替代方案是声明一个临时变量来承载你所需要的属性。
(function(){
// vue中的解决方案
'use strict'
console.log('this1:',this);
new Function('with(this){console.log(123)}')();
})();
console.log('this2:',this)
网友评论