Question

Can I do this ?

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

If not why ? Are there any alternative methods ?

Was it helpful?

Solution

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'

OTHER TIPS

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

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

to save your function at browser level.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top