在JS中覆盖分配运算符 [英] Overriding assignment operator in JS

查看:107
本文介绍了在JS中覆盖分配运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var myObject = {"myKey" : "myValue"}
typeof(myObject.myKey) returns `string`

myObject.myKey = "newValue"
console.log(myObject.myKey) prints newValue

行为。但是,类似的值写不适用于document.cookie

This is the expected behavior. But, similar value writes do not work for document.cookie

typeof(document.cookie) returns `string`

但执行 document.cookie =value = 123附加到 document.cookie 字符串,而不是将其值设置为 value = 123

But performing document.cookie = "value=123", appends to document.cookie string rather than set its value to value=123

那么,如何重载 document.cookie 的赋值

推荐答案

document.cookie 有点神奇,但根据浏览器的限制,您可以使用 Object.defineProperty 定义具有不同 get

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.

例如:

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}'






例如,要做类似于cookie示例的操作,可以创建一个函数:


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];
      }
    }
  });
})

这将在 data 属性中混合,以扩展 setter 进入私有对象。 getter 将返回它的序列化版本。然后你可以使用它:

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} 

这篇关于在JS中覆盖分配运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆