最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Overriding assignment operator in JS - Stack Overflow

programmeradmin1浏览0评论
var myObject = {"myKey" : "myValue"}
typeof(myObject.myKey) returns `string`

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

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

typeof(document.cookie) returns `string`

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

So, how is assignment to document.cookie overridden?

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

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

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

typeof(document.cookie) returns `string`

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

So, how is assignment to document.cookie overridden?

Share Improve this question asked Mar 10, 2014 at 19:34 zodvikzodvik 9212 gold badges9 silver badges22 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 19

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} 

Browser-supplied host objects behave in ways that are not constrained by the semantics of the language. That is, document looks like a JavaScript object, but it's not. It's part of the runtime environment.

The JavaScript spec is written in terms of various internal "method" descriptions. Host objects like window and document have special versions of those internal methods. Thus, the runtime follows the spec as to how the = assignment process works, but the internal method [[Put]] is simply special.

发布评论

评论列表(0)

  1. 暂无评论