Skip to content

Instantly share code, notes, and snippets.

@leeluolee
Created June 9, 2015 12:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leeluolee/ffc5cbd1843d430c7363 to your computer and use it in GitHub Desktop.
Save leeluolee/ffc5cbd1843d430c7363 to your computer and use it in GitHub Desktop.
keyOf讨论
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
var 有啥卵用 = function(){
var x = {foo:1}
var something = 'something';
var somethingKey = keyOf({something: ''});
x.something = function(){
console.log('haha');
}
x[somethingKey](); // 不报错
x[something](); // 报错, 因为key被压缩了
}()
// 步骤
//
// 1. 使用最新版的uglifyjs, npm install npm install uglify-js@2.4.23 -g
// 2. 复制上述代码为file1.js
// 3. 开启 mangleProperties (--mangle-props).
// 部分符合的键值会被压缩(明显不安全的做发)...
// 3. 分别注释1和2. 使用 uglifyjs file1.js --mangle-props --mangle
// 4. 复制输出的代码到浏览器运行, 你会发现somethingKey 不报错, 但是something报错了
// 5. 这是由于键值被压缩,而字符串没压缩
// 6. 综上所述, 就是 “运行时拿到被压缩的键值”. 其实就是“没啥卵用”
// 代码1 输出
$ uglifyjs file1.js --mangle-props --mangle
var keyOf=function(n){var r;for(r in n){if(!n.hasOwnProperty(r)){continue}return r}return null};var 有啥卵用=function(){var n={a:1};var r="something";n.b=keyOf({c:""});n.c=function(){console.log("haha")};n[r]()}();
// 代码2 输出
$ uglifyjs file1.js --mangle-props --mangle
var keyOf=function(n){var r;for(r in n){if(!n.hasOwnProperty(r)){continue}return r}return null};var 有啥卵用=function(){var n={a:1};var r="something";var a=keyOf({b:""});n.b=function(){console.log("haha")};n[a]()}();
@leeluolee
Copy link
Author

image

只能说城里人真会玩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment