JavaScript:从MutationObserver访问类
鉴于以下类别:JavaScript:从MutationObserver访问类,javascript,Javascript,鉴于以下类别: function MyCustomClass(e){ this.element = e; this.start(){ var observer = new MutationObserver(this.mutationObserved), config = { attributes: true }; observer.observe(this.element, co
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
类运行的类
这个。另一个函数
不起作用,因为作用域现在在MutationObserver
类中。尝试以下操作:
//...
var self = this;
this.mutationObserved = function(e){
self.anotherFunction();
}
您需要捕获外部函数的上下文,然后在内部函数中使用它