Overriding assignment operator in JS

前端 未结 2 658
被撕碎了的回忆
被撕碎了的回忆 2021-02-09 00:07
var myObject = {\"myKey\" : \"myValue\"}
typeof(myObject.myKey) returns `string`

myObject.myKey = \"newValue\"
console.log(myObject.myKey) prints newValue
2条回答
  •  醉话见心
    2021-02-09 00:23

    document.cookie is a little magical, but depending on your browser constraints, you an use Object.defineProperty to define properties that have different get and set behavior.

    For example:

    var obj = {};
    
    Object.defineProperty(obj, "data", {
        get: function() {return this.val; },
        set: function(val) { this.val = JSON.stringify(val); }
    });
    
    obj.data = {a:1}; // Set as an object...
    console.log(obj.data) // but retrieve as string '{"a":1}'
    

    For example, to do something similar to the cookie example, you could make a function like:

    var mixinExtender = (function mixinExtender(target) {
      var rawValue = {};
    
      Object.defineProperty(target, "data", {
        get: function() { return JSON.stringify(rawValue); },
        set: function(val) { 
          for(var key in val) {
            rawValue[key]  = val[key];
          }
        }
      });
    })
    

    This will mixin in a data property that will extend the setter value into a private object. The getter will return a serialized version of it. Then you could use it with:

    var obj = {};
    mixinExtender(obj);
    
    obj.data = {a:1};      // Add "a" key
    obj.data = {b:2};      // Add "b" key
    console.log(obj.data)  // > {"a":1,"b":2} 
    

提交回复
热议问题