JavaScript의 스토리지 클래스에 사용자 정의 메소드를 추가하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/20353420

  •  25-08-2022
  •  | 
  •  

문제

이걸 할 수 있나요?

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