Created
June 9, 2015 12:44
-
-
Save leeluolee/ffc5cbd1843d430c7363 to your computer and use it in GitHub Desktop.
keyOf讨论
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]()}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
只能说城里人真会玩