2017-03-21 7 views
0

Object의 프로토 타입 메서드 인 함수를 덮어 쓰려고합니다. 이 방법은 내부적으로 this을 사용합니다. 어떻게 그 기능을 덮어 쓸 수 있지만, 원래 함수에서와 같이 this을 동일한 객체/값으로 정의 된 상태로 유지 하시겠습니까?Javascript가 메소드를 덮어 씀과 같은 것을 유지합니까?

내가 그것을 유지하려는 이유는 다음과 같다 :

  • 원래 코드는 확장을 지원합니다. 차라리 확장을 작성하고 원본 코드의 작성자가 의도 한대로 코드에 추가하는 것이 원본 코드를 변경하고 수정 된 버전을 빌드하거나 설치하는 것보다 좋습니다.
  • 원본 함수가 호출되기 전에 항상 일부 작업을 수행해야합니다. 그래서 실제로 원래의 기능을 유지하고 싶지만 그 전에 뭔가 추가하고 싶습니다. 필자는 이것이 파이썬의 데코레이터처럼 함수를 "장식"한다고 생각합니다.
  • 함수에서 덮어 쓰는 코드의 범위가 원래 정의 된 것과 다릅니다. 내가 그렇게 할 때, 나는 TypeErrorthisthis를 사용하여 원래의 함수의 첫 번째 줄에 정의되지 않는다는 것을 말해 얻을, 그러나

    //original functions 
    var original_execute_cells = Jupyter.Notebook.prototype.execute_cells; 
    
    // decorating functions 
    function decorated_execute_cells(cell_indices) { 
        console.log('EXTENSION: running decorated execute_cells function'); 
        return original_execute_cells(cell_indices); 
    } 
    
    // overwrite original functions 
    Jupyter.Notebook.prototype.execute_cells = decorated_execute_cells; 
    

    : 여기

몇 가지 예제 코드입니다 .

내가 덮어 쓰기를 시도하고 함수의 원래 소스 코드 github에서 찾을 수 있습니다 :

Notebook.prototype.execute_cells = function (indices) { 
    if (indices.length === 0) { 
     return; 
    } 

    var cell; 
    for (var i = 0; i < indices.length; i++) { 
     cell = this.get_cell(indices[i]); 
     cell.execute(); 
    } 

    this.select(indices[indices.length - 1]); 
    this.command_mode(); 
    this.set_dirty(true); 
}; 
+2

do 'original_execute_cells.call (this, cell_indices)' – slebetman

+1

참조 : http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object -literal/13441628 # 13441628 – slebetman

답변

0

지금 bind로했다. return 문이된다 :

return original_execute_cells.bind(Jupyter.notebook)(cell_indices); 

어디 Jupyter.notebook 내 특정 경우에 Notebook 개체가 빌드는 개체에 관련된 this이다.

그러나 @siebetman이 주석에서 언급 한 내용도 작동 할 수 있으며 경우에 따라 더 유연해질 수도 있습니다. 또한 제공된 siebetman 링크는 Javascript의 this을 더 잘 이해하는 데 매우 유용합니다.

관련 문제