IntersectionObserver: "Uncaught TypeError: Cannot read property of undefined" when called onIntersection()
IntersectionObserver: "Uncaught TypeError: Cannot read property of undefined" when called onIntersection()
我有以下代码:
var ObjectOne = {
a : {
b : 4,
...
}
observer : 0,
...
init() {
this.a.b = 5;
...
this.observer = new IntersectionObserver(this.onIntersection, ...);
this.observer.observe(...);
...
}
onIntersection(entries, observer) {
...
var test = this.a.b;
...
}
}
而当 运行 它时,我在执行 onIntersection() 时出现错误。错误是:Uncaught TypeError: Cannot read 属性 'b' of undefined。我如何将 ObjectOne 的 'this' 实例传递给 onIntersection() 函数?
感谢Heretic Monkey for useful link How to access the correct this
inside a callback? - it was helpful and give me a direction for search. And more helpful information was at Use of the JavaScript 'bind' method。添加bind()函数解决问题:
var ObjectOne = {
a : {
b : 4,
...
}
observer : 0,
...
init() {
this.a.b = 5;
...
this.observer = new IntersectionObserver(this.onIntersection.bind(this), ...);
this.observer.observe(...);
...
}
onIntersection(entries, observer) {
...
var test = this.a.b;
...
}
}
我有以下代码:
var ObjectOne = {
a : {
b : 4,
...
}
observer : 0,
...
init() {
this.a.b = 5;
...
this.observer = new IntersectionObserver(this.onIntersection, ...);
this.observer.observe(...);
...
}
onIntersection(entries, observer) {
...
var test = this.a.b;
...
}
}
而当 运行 它时,我在执行 onIntersection() 时出现错误。错误是:Uncaught TypeError: Cannot read 属性 'b' of undefined。我如何将 ObjectOne 的 'this' 实例传递给 onIntersection() 函数?
感谢Heretic Monkey for useful link How to access the correct this
inside a callback? - it was helpful and give me a direction for search. And more helpful information was at Use of the JavaScript 'bind' method。添加bind()函数解决问题:
var ObjectOne = {
a : {
b : 4,
...
}
observer : 0,
...
init() {
this.a.b = 5;
...
this.observer = new IntersectionObserver(this.onIntersection.bind(this), ...);
this.observer.observe(...);
...
}
onIntersection(entries, observer) {
...
var test = this.a.b;
...
}
}