注入(inject)后能拿到 key 吗?
var outside=[];
var NULL=(function(){
var key='';
console.log("Hi, I'm null!");
window.injectkey=function(k){
window.injectkey=null;
key=k;
return;
};
window.askmeforkey=function(){return "nope! I could use my key for stuff though...";}
setTimeout(function(){
outside.push("I still exist and can alter things outside but you can't see me!");
console.log(outside);
},1000);
})();
NULL=null;
console.log('NULL=='+NULL); // prints NULL==null
尝试后
console.dir(NULL); // prints null
injectkey('xyz');
再来一次
injectkey('abc'); // Uncaught TypeError: injectkey is not a function(…)
askmeforkey() // nope
可能的用途:(假设 key 可能是未在任何地方硬编码的加密 key )
injectkey
可以通过一些安全的加密消息传递以多种方式完成
最佳答案
key
对于匿名函数来说是完全私有(private)的。请注意,这里根本不需要 NULL
,这会执行完全相同的操作:
var outside=[];
(function(){
var key='';
console.log("Hi, I'm null!");
window.injectkey=function(k){
window.injectkey=null;
key=k;
return;
};
window.askmeforkey=function(){return "nope! I could use my key for stuff though...";}
setTimeout(function(){
outside.push("I still exist and can alter things outside but you can't see me!");
console.log(outside);
},1000);
})();
这是避免过度暴露变量的常见模式。
关于javascript - 像这样将代码隐藏在 null 中安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39777446/