2016-11-24 66 views
-1

訪問類考慮下面的類:的JavaScript:從MutationObserver

function MyCustomClass(e){ 

    this.element = e; 

    this.start(){ 

     var observer = new MutationObserver(this.mutationObserved), 
     config = { 
       attributes: true 
     }; 
     observer.observe(this.element, config); 

    } 

    this.anotherFunction = function(){ 
     console.log("Another function was called"); 
    } 

    this.mutationObserved = function(e){ 
     // This doesn't work 
     this.anotherFunction(); 
    } 
} 

如何訪問其中mutationObserved類操作類?

this.anotherFunction不起作用,因爲範圍現在在MutationObserver類中。

+0

['Function.prototype.bind'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – Andreas

回答

0

試試這個:

//... 
var self = this; 
this.mutationObserved = function(e){ 
    self.anotherFunction(); 
} 

您需要捕捉外部函數的上下文,然後在內部一個使用它。