[英]How to call a object method without object instance?
我有一個方法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
}
};
如果loadSet
不需要或不使用實例,則將其放在ReminderSet.prototype
上沒有任何意義。 使其成為獨立功能:
function loadSet() {
// ...
}
// Call it like so: loadSet();
...或ReminderSet
本身的屬性:
ReminderSet.loadSet = function() {
// ...
};
// Call it like so: ReminderSet.loadSet();
只放一個構造函數的對象上的功能prototype
屬性是指如果他們需要使用this
(實例)。
您可以將函數直接設置為另一個ReminderSet
的屬性:
ReminderSet.loadSet = function() {//etc.}
然后,您可以簡單地調用: ReminderSet.loadSet()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.