覆盖特定对象中的本机方法和对象

时间:2013-03-02 06:28:40

标签: javascript

我正在尝试为一个对象INSIDE覆盖名为“localStorage”的本地方法。

以下是我要做的事情的要点:

function SomeObject(){
   this.localStorage = "aaa"; //block access to localStorage for functions INSIDE this object.
      ... (some more code here)
   _testRun(){
      window.testA = localStorage; //chose to store the instance on a window (global-like) object
   }
   this.testRun = function(){ _testRun(); };
   this.testRun2 = function(){ window.testB = localStorage;};v
}
var a = new SomeObject();
a.testRun();
a.testRun2();

(after this, when I look up window.testA and window.testB, they both point to the Native localStorage, not the custom one inside the SomeObject.)

顺便说一句,我不想​​覆盖整个文档的本机函数。 (即可能使用本地localStorage OUTSIDE对象)

关于我如何做到这一点的任何建议/解决方案?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试添加window.localStoragethis.localStorage,而不仅仅是localStorage

function SomeObject(){
   this.localStorage = "aaa"; //block access to localStorage for functions INSIDE this object.
      ... (some more code here)
   _testRun(){
      window.testA = window.localStorage; //chose to store the instance on a window (global-like) object
   }
   this.testRun = function(){ _testRun(); };
   this.testRun2 = function(){ window.testB = this.localStorage;};
}