将代码隐藏在null中是否安全?

时间:2016-09-29 18:24:29

标签: javascript null

注册后你能拿到钥匙吗?

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

可能的用途:(假设密钥可能是未在任何地方进行硬编码的加密密钥)

injectkey可以通过一些安全的加密消息传递以多种方式完成

1 个答案:

答案 0 :(得分:2)

key对匿名函数完全是私有的。请注意,这里根本不需要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);
    })();

这是避免比必要更广泛地暴露变量的常见模式。