如何在没有对象实例的情况下调用对象方法?

时间:2017-10-22 16:55:21

标签: javascript

我有一个方法loadSet,它使用localstorage中的数据创建元素,这应该在页面加载时运行我通过

调用它
  

ReminderSet.prototype.loadSet(); //工作正常

我的问题是,有没有其他方法可以调用不需要引用对象实例的方法?比如person1.loadSet();或者我应该放弃这个并将其作为常规功能吗?

ReminderSet.prototype.loadSet = function() {
    var keys = Object.keys(localStorage),
        i = 0,
        key,
        array;

    for (; key = keys[i]; i++) {
        const setId = localStorage.getItem(key);
        array = JSON.parse(setId); //parse and store key values
        let array_index = 0;
        //Re-create the reminders and set their properties//
        $reminderSection.append($('<div/>').addClass('set').attr('id', key) //Set the ID                      
            .append($('<div/>').addClass('set-title').append($('<h1>').attr('contenteditable', 'true').text(array[array_index].set_title)), //Index is always at 0//
                $('<div/>').addClass('create-reminder-control').append($('<button>').addClass('add-new-reminder').text("+ add new"), $('<input>').addClass('create-reminder-value').attr({ type: "text", placeholder: "get something done" })), $('<div/>').addClass('reminder-lists'), $('<div/>').addClass('save-control').append($('<button>').addClass('save-reminder-button').text('Save'))))

        //Get our key values //
        for (; array_index < array.length; array_index++) {
            /*Select the element id */
            $("#" + key).children('.reminder-lists').append($('<div/>').addClass('a-reminder').attr('contenteditable', 'true').text(array[array_index].description).append($('<div/>').addClass('delete-reminder').text('x'))) //Get the reminders
        } //end

    }
};

2 个答案:

答案 0 :(得分:2)

如果loadSet不需要或不使用某个实例,则ReminderSet.prototype上没有任何意义。要么使它成为一个独立的功能:

function loadSet() {
    // ...
}
// Call it like so:  loadSet();

...或ReminderSet本身的财产:

ReminderSet.loadSet = function() {
    // ...
};
// Call it like so:  ReminderSet.loadSet();

如果需要使用prototype(实例),只将函数放在构造函数的this属性所引用的对象上。

答案 1 :(得分:1)

您可以将该功能直接设置为其他ReminderSet的属性:

ReminderSet.loadSet = function() {//etc.}

然后您只需致电:ReminderSet.loadSet()

相关问题