JavaScript:来自MutationObserver的访问类

时间:2016-11-24 16:05:05

标签: javascript

鉴于以下课程:

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类中。

1 个答案:

答案 0 :(得分:0)

试试这个:

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

您需要捕获外部函数的上下文,然后在内部函数中使用它。