2015-02-02 2 views
1

DOM 요소에서 setter 메서드를 사용하도록 설정하는 방법을 찾고 있습니다. 그래서 기본적으로이 특정 속성에 대한 모든 호출을 차단하려고합니다. 나는 특정 DOM 요소를 GET/SET 속성을 정의하는 시도했지만, 훨씬 도움이되지 않습니다 :innerHTML 속성 액세스 무시

document.body.innerHTML = 'testValue'; 

입니다 :

(function(object, property) { 
    var __value; 
    Object.defineProperty(object, property, { 
     // Create a new getter for the property 
     get: function() { 
      console.log('access gettter'); 
      return __value; 
     }, 
     // Create a new setter for the property 
     set: function (val) { 
      __value = val; 
     } 
    }) 
})(document.body, 'innerHTML'); 

이의 결과는 호출하는 것입니다

document.body.innerHTML 
access gettter 
"testValue" 

그러나 이것은 페이지에 영향을주지 않으며, 페이지 본문이 변경되지 않았 음을 나타냅니다. 클로저 내부의 개인 변수 값만 반환됩니다. 자바 스크립트에서이 기능을 구현할 수있는 방법이 있습니까?

+2

왜 그렇게할까요? –

+0

호스트 개체를 변경하는 것은 잘못된 생각입니다. http://perfectionkills.com/whats-wrong-with-extending-the-dom/ –

답변

3

예, 가능합니다. 다음은 작동하는 코드의 코드입니다.

(function(object, property) { 
    var ownObjectProto = Object.getPrototypeOf(object); 
    // exit if bad property 
    if (!object[property]) { 
     console.error(property + " is not a property of " + object.toString()); 
     return; 
    } 

    while (!Object.getOwnPropertyDescriptor(ownObjectProto, property)) { 
     ownObjectProto = Object.getPrototypeOf(ownObjectProto); 
    } 

    var ownProperty = Object.getOwnPropertyDescriptor(ownObjectProto, property); 
    Object.defineProperty(object, property, { 
     // Create a new getter for the property 
     get: function() { 
      console.log('access gettter'); 
      return ownProperty.get.call(this); 
     }, 
     // Create a new setter for the property 
     set: function (val) { 
      return ownProperty.set.call(this, val); 
     } 
    }) 
})(document.body, 'innerHTML'); 

실제로 여기에 세트를 가져 오지 않고 기능을 가져 오지는 않지만 기능을 향상시킬 수 있습니다. 진지하게도, 당신이 그것을 특별히 필요로하지 않는다면 이것을 사용해서는 안되며, 당신이하는 일을 정말로 알고 있습니다. 올바르게 사용하지 않으면 플러그인이나 다른 의도하지 않은 결과의 기능을 엉망으로 만들 수 있습니다.

여기에도 운동장이 있습니다. jsfiddle