我可以这样做吗?

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

如果不是,为什么?有其他方法吗?

有帮助吗?

解决方案

我将非常谨慎地修改这样的对象的行为。通常最好为LocalStorage提供包装器(或使用 Store.js 或其他库)提供您想要的功能。

在你的情况下 想要将方法或属性添加到LocalStorage中,您可以通过将其添加到构造函数的原型中来做到这一点:

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'

其他提示

你为什么要做这样的事情?利用:

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

为了在浏览器级别保存您的功能。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top