Is it possible to create a hidden property in javascript

前端 未结 6 2060
刺人心
刺人心 2020-12-08 04:59

I want to create an object with a hidden property(a property that does not show up in a for (var x in obj loop). Is it possible to do this?

6条回答
  •  醉话见心
    2020-12-08 05:47

    It's a bit tricky!

    function secret() {
      var cache = {};
      return function(){
        if (arguments.length == 1) { return cache[arguments[0]];}
        if (arguments.length == 2) { cache[arguments[0]] = arguments[1]; }
      };
    }
    var a = secret();
    
    a.hello = 'world';
    a('hidden', 'from the world');
    

    If you are a real pro though, you can do it this way!

    var a = new (secret())();
    
    a.hello = 'world';
    a.constructor('hidden', 'from the world');
    

    Now if you look a in firebug it will be an object ... but you know better! ;-)

提交回复
热议问题