简体   繁体   中英

How can I add custom method to storage class in Javascript

Can I do this ?

localStorage.myfunction = function () { ... }

If not why ? Are there any alternative methods ?

I would be very very careful with modifying the behaviour of objects like this. It is typically better to provide a wrapper for localStorage (or use store.js or another library) to provide the features you want.

In the case that you do want to add a method or property to localStorage, you can do so by adding it to it's constructor's prototype:

typeof(localStorage.prototype); // "undefined"
localStorage.constructor // function Storage() { [native code] }

Storage.prototype.foo = function () { return 'foo'; }
// setting a method on the constructor allows each localStorage instance
// to inherit and use it 
localstorage.foo() // 'foo'

Why do you want to do something like this? use:

window.myfunction = function(){
    // do stuff here
};

to save your function at browser level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM