今天使用百度分享的一段代码,看到有这么一句(可能是机器生成的):
with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)]
奇怪的地方是:
with(..)0[];
这段,经测试:
with({a : 1, b : 2})0[console.log(a)];
在控制台输出:
1
undefined
如果这样:
with({a : 1, b : 2})[console.log(a)];
在控制台输出:
1
[Object { __exposedProps__={...}, toString=function()}]
期待有朋友帮忙解释:
with()0[]
这段代码应该如何理解的??
with(...)0[...]
等价于:
with(...) {
0[...];
}
其中 0[...]
是一个看起来很诡异但是合法的 javascript 代码,无非就是调用 0 这个对象的方法。比如 0["toString"]
返回的就是一个函数,等同于 0.toString
。
所以总的来说,这句话就是为了执行方括号里面的代码,为了少写一个 document
节省几个 bytes 而发明的变态写法,应该是百度内部用的脚本混淆器干的好事。
不过很奇怪,其实 0[...]
根本就是多余的啊~直接写 with{...}
明明还可以多省一个字节,为啥百度不用呢。对于题主贴出来的这行代码,连 {...}
都可以直接省了。想不通。
// 这真的是合法的代码
with(document)getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)
a=0;
a["toString"];
0["toString"];
b=console.log(4);
a[b]; // a[undefined]
a[console.log(4)]; // 当然返回undefined啦
with ({p:4}) console.log(p); //with 后面可以跟语句,多条语句才需要{}啊。
with ({p:4}) a[p];
with ({p:4}) a[console.log(p)];
with ({p:4}) 0[console.log(p)]; //返回undefined
结论,如果这代码是人写的,那他一定需要治疗。