search

Home  >  Q&A  >  body text

javascript - Is there any good way to encapsulate parts like this? ~

Now I feel like it’s not good to write everywhere. What if I want to change my name that day? Should I replace them one by one? ~

typechotypecho2779 days ago647

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-06-12 09:33:17

    Or you can write an intermediary function to handle the addition, deletion, modification and query of related variables? Let’s see if others have a better way

    var o = {
        data : {},
        add : function(key,val){
           if(!key) return false;
           var data = this.data;
           data[key] = data[key] || {};
           data[key] = val;
        },
        del : function(key){
            if(!key) this.data = {};
            delete this.data[key];
        },
        changeVal : function(obj){
            if( Object.prototype.toString.call(obj) != '[object Object]' )
            obj = {};
            
            var data = this.data;
            for( var key in obj){
                if(data[key]){
                    data[key] = obj;
                }
            }
        }
        //.......
        //写了个简单的,如果要求更复杂可以自己去拓展
    };

    It’s a bit difficult to get the value. If you want to assign the value, you can create a new function for the assignment. If you want to modify the value, just call the function directly,

    reply
    0
  • 三叔

    三叔2017-06-12 09:33:17

    Encapsulated into an object

    reply
    0
  • Cancelreply