javascript - 从原型(prototype)方法更改实例属性

标签 javascript class oop methods prototype

我正在尝试构建一个可重复使用的 Database具有原型(prototype)方法的类,用于将项目添加到类的 list数组属性:

    var Database = function() {
        this.list = [];
    }

    Database.prototype = {
        getBooks: function () {
            $.get("//some.url/books")
            .success(function(res) {
                _.each(res,function(book) {
                    this.list.push({
                        name: book.name,
                        url: book.url,
                        type: "book"
                    })
                })
            });
        }
    }

但是,目前我收到一条警告,说我无法推送到未定义的属性 list ,我只能假设我实际上不是 .push任何 Database类实例属性,而不是原型(prototype)属性。

那么,问题又来了:如何使用原型(prototype)方法来更改实例的属性?

最佳答案

您可以将 this 的引用存储在变量中,如下所示

 Database.prototype = {
        getBooks: function () {
           var _this = this;
            $.get("//some.url/books")
            .success(function(res) {
                _.each(res,function(book) {
                    _this.list.push({
                        name: book.name,
                        url: book.url,
                        type: "book"
                    })
                })
            });
        }
    }

关于javascript - 从原型(prototype)方法更改实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28237641/

相关文章:

java - 从派生类创建基类对象

c++ - 为什么静态成员初始化需要是 "typed again"?

java - 如何通过继承来访问string的值?

javascript - chrome.serial/chrome.usb 未定义

javascript - 如何仅显示视频链接列表并使用 Youtube 搜索 API 进行播放

javascript - Angular JS 和指令链接和 $timeout

javascript - 如何防止段落中的行被删除(Javascript替换正则表达式)

c++ - 在 GCC 中为类使用属性打包

Java无法重写构造函数中使用的方法: The method setupAnimationFrames() of type Slime must override or implement a supertype method

c++ - 如何在循环中访问数组对象的成员函数