Javascript函数没有被添加到对象原型中

Javascript functions not being added to the object prototype

本文关键字:对象 原型 添加 函数 Javascript      更新时间:2023-09-26

我有几个在我的代码中向javascript类添加原型的其他实例,这些实例工作得很好,我无法确切地弄清楚为什么我刚刚写的部分拒绝工作。
问题的部分是:

var opt = new Settings;
function Settings() {
    this.initjQuerySelectors();
    this.sorted_columns_url = this.getSortedColumnsUrl();
}
Settings.prototype.initjQuerySelectors = function() {
    this.data_store_selector = $('.data_store.display');
};
Settings.prototype.getSortedColumnsUrl = function() {
    return this.data_store_selector.val();
};

,并产生以下错误:

Uncaught TypeError: Object #<Settings> has no method 'initjQuerySelectors' 

当我试图捕获错误时,它指出也没有getSortedColumnsUrl();的方法。

用chrome开发工具查看代码,它显示我添加的设置原型中确实没有任何内容,问题是我无法找出原因。

这可能是因为您的代码顺序不正确,

尝试先定义原型,然后再实例化opt对象。

Settings.prototype.initjQuerySelectors = function() {
    this.data_store_selector = $('.data_store.display');
};
Settings.prototype.getSortedColumnsUrl = function() {
    return this.data_store_selector.val();
};
function Settings() {
    this.initjQuerySelectors();
    this.sorted_columns_url = this.getSortedColumnsUrl();
}
var opt = new Settings;
编辑:

在扩展它的原型以完全跨浏览器支持之前定义函数。(感谢@Turnerj修复)