0

Is this possible? The real world example is here:

var userKey = "userIdKey";

chrome.storage.sync.set({ userKey: "Hello World" }, function () {
    chrome.storage.sync.get(userKey, function (data) {
        console.log("In sync:", data);
    });

    console.log("Success");
});

This example currently fails because the getter looks for "userIdKey" where as the setter interprets the variable literally as "userKey"

UPDATE: I am fully aware of accessing a variable via array notation. The realworld example I have provided is for the creation of the object. I am hoping to ensure that the same key is always used for getting and setting -- rather than relying on two string constants being kept in sync.

4

3 回答 3

1
var myObject = {},
    objectKey = 'Foo',
    myObject[objectKey] = 'Baz';

console.log(myObject[objectKey]);
于 2013-05-01T23:24:32.120 回答
1

正确的方法是:

    var key = "something";
    Object.defineProperty(d, key, {
        get: function() {return this.getFullYear() },
        set: function(y) { this.setFullYear(y) }
    });

或者在你的情况下:

chrome.storage.sync.defineProperty(this, userKey, {
    get: function() {return this[userKey];},
    set: function(value) {this[userKey] = value};
});

阅读此处了解更多信息。Object.prototype.defineProperty是新的,在传统模式下不可用,但 polyfill 可用作Object.prototype.__defineGetter__Object.prototype.__defineSetter__.

于 2013-05-01T23:26:13.457 回答
0

像数组一样访问它:

myObject['Foo']

设置:

myObject['Foo'] = "Bar"

或作为变量:

var key = "Foo";
myObject[key] = "Bar"
于 2013-05-01T23:22:23.313 回答