如何在Javascript中向存储类添加自定义方法

How can I add custom method to storage class in Javascript

本文关键字:存储 添加 自定义方法 Javascript      更新时间:2024-02-04

我能做到这一点吗?

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

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

我会非常小心地修改这样的对象的行为。通常最好为localStorage提供一个包装器(或者使用store.js或其他库)来提供您想要的功能。

如果do想要将方法或属性添加到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
};

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