方法,不设置属性值

Method, doesn't set property value

本文关键字:属性 设置 方法      更新时间:2023-09-26

我有以下代码:

function Show() {
    this.showId = $("#meta-show-id").val();
    this.title = $("#meta-title").val();
    this.season = $("#meta-season").val();
    this.episode = $("#meta-episode").val();
    this.storageId = $("#meta-show-id").val() + '-' + $("#meta-season").val() + '-' + $("#meta-episode").val();
    this.torrents = [];
    this.putioId = null;
    this.status = null;
    this.subtitle = null;
}
Show.prototype = {
    constructor: Show,
    checkStorage: function() {
        var storage = new Storage();
        storage.get(this.storageId, function(data){
            if (jQuery.isEmptyObject(data)){
                console.log("empty");
            }
            else {
                this.subtitle = data.subtitle;
            }
        });
    }
}

当我在object上调用checkStorage()方法时,方法在chrome.storage.sync中检查数据,并设置object this.subtitle property

但这似乎不起作用,this.subtitle值没有改变。

我做错了什么?

这是正常的结果,因为作用域发生了变化。我不知道Storage是否有你自己的实现(因为它与getItem而不是get一起使用),但无论如何,你正在调用一个方法,我猜回你作为第二个参数提供的函数,对吧?

因为这个函数是从其他地方调用的,所以this不是你想要的对象。

下面是一个简单的例子:http://jsfiddle.net/6c2e6/1/

检查日志,看看this是什么。这是窗口,因为我的test函数是在顶层…