FF 13, IE 9: JSON stringify / geolocation object

可紊 提交于 2019-11-27 15:07:12

What's going on is that JSON.stringify only looks at the object's own properties by default.

And per DOM specs all DOM properties actually live on the object's prototype.

IE and Firefox implement the spec correctly by putting the properties on the prototype. Chrome and Safari do not: they put the properties directly on the object. That makes this case work, but breaks other things (e.g. the ability to hook the property getters and setters)....

There's talk of adding toJSON methods to some DOM objects to give them more reasonable behavior for JSON.stringify.

I created a clone function to clone the Geolocation position (or any other) object into an object that will be stringified as expected:

function cloneAsObject(obj) {
    if (obj === null || !(obj instanceof Object)) {
        return obj;
    }
    var temp = (obj instanceof Array) ? [] : {};
    // ReSharper disable once MissingHasOwnPropertyInForeach
    for (var key in obj) {
        temp[key] = cloneAsObject(obj[key]);
    }
    return temp;
}

Note: May not support types not used in Geoposition type (eg Date)

You would then use it as follows in your code:

var gps = JSON.stringify(cloneAsObject(position)); 

Hope this helps someone :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!