Javascript,访问object.property

时间:2012-02-23 12:30:09

标签: javascript oop google-chrome google-chrome-extension backbone.js

在我的代码中this.options返回嵌套了.all对象的对象。然而,当我尝试使用this.options['all']this.options.all访问它时,我得到undefined

console.log(this.options):

Object
    all: Object
        cfg_autoresize: "true"
        cfg_autosave: "false"
        cfg_monthly_target: "monthly_target"
        cfg_statistics: "statistics"
        cfg_ticker: "ticker"
        cfg_yearly_target: "yearly_target"
    __proto__: Object

有人可以帮我解决这个问题吗,以前从未遇到过这个问题。感谢

编辑:

content_script,简化版

var Dashboard = Backbone.View.extend({
    el: $('body'),
    options: {},

    get_localStorage: function() {
        var _this = this;
        function handle_response(response) {_this.options.all = response.data;}
        chrome.extension.sendRequest({method: "allLocalStorage"}, handle_response);
    },

    initialize: function() {
        this.get_localStorage();
        console.log(this.options); // above object
        console.log(this.options.all); //undefined
    }
});

background.html,取自Google-chrome-extension文档并已修改

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.method == "allLocalStorage") {

        var options = {};

        for (var i=0, l=localStorage.length; i<l; i++){
            var key = localStorage.key(i);
            var value = localStorage[key];
            options[key] = value;
        }

        sendResponse({data: options}); 

    } else {
        sendResponse({}); 
    }
});

理想情况下,我希望this.options包含.all内的所有选项,但它对我不起作用。

1 个答案:

答案 0 :(得分:1)

你能告诉我们一些似乎不正确的js代码(声明和对象访问)吗?

修改

啊,我看到...当你调用get_localStorage();由于handle_response函数在sendRequest完成之前尚未触发,因此可能没有初始化该对象。

您可能想尝试以下内容:

get_localStorage: function(callback) {
    var _this = this;
    function handle_response(response) {
        _this.options.all = response.data;     
        callback(_this.options);
    }
    chrome.extension.sendRequest({method: "allLocalStorage"}, handle_response);
}

initialize: function() {
    this.get_localStorage(function(op) {
            console.log(op);
            console.log(op.all);
        }
    );
}