![](/img/trans.png)
[英]How do I pass a function using “this” keyword into a JavaScript Class?
[英]how to pass this keyword to javascript class functions
尝试从另一个函数init
访问this.numberObject
时,我undefinded
了undefinded
错误。
我很确定这是因为我的this
关键字引用了 window 对象。
我的问题是我想不出一种优雅的方式来构建我的代码。
当前代码:
class IncrementNumbers {
constructor() {
this.numberObject = document.querySelector(".incrementNum");
if (this.numberObject != null) {
console.log(this.numberObject.innerHTML);
this.num = this.numberObject.innerHTML;
this.events();
}
}
events() {
console.log("events function ran");
this.init();
}
init() {
let target = 345;
let current = 0;
function addOneToElement() {
if (current === target) {
clearInterval(addOne);
}
current++;
this.numberObject.innerHTML = current; <---- ERROR HERE
}
let addOne = setInterval(addOneToElement, 10);
}
}
export default IncrementNumbers;
错误:
IncrementNumbers.js:44 Uncaught TypeError: Cannot set property 'innerHTML' of undefined
我可以通过添加来修复错误
this.numberObject = document.querySelector(".incrementNum");
到以下功能
init() {
let target = 345;
let current = 0;
function addOneToElement() {
this.numberObject = document.querySelector(".incrementNum"); <--- ADDED HERE
if (current === target) {
clearInterval(addOne);
}
current++;
this.numberObject.innerHTML = current;
}
let addOne = setInterval(addOneToElement, 10);
}
然而,这感觉有点多余,因为我已经在我的构造函数中引用了元素 Object。 我希望函数init
在页面加载后运行。
有没有更好的办法?
谢谢
您的问题似乎来自this
对象的错误传播。
在您的函数init
您设置了一个名为addOneToElement
的新函数,该函数在setInterval
内setInterval
,此setInterval
instance
无权访问您的class
的this
元素。
要解决此问题,您可以尝试执行以下操作
class IncrementNumbers {
constructor() {
this.numberObject = document.querySelector(".incrementNum");
if (this.numberObject != null) {
console.log(this.numberObject.innerHTML);
this.num = this.numberObject.innerHTML;
this.events();
}
}
events() {
console.log("events function ran");
this.init();
}
init() {
let target = 345;
let current = 0;
function addOneToElement() {
if (current === target) {
clearInterval(addOne);
}
current++;
this.numberObject.innerHTML = current; // <---- ERROR HERE
}
let addOne = setInterval(addOneToElement.bind(this), 10);
}
}
export default IncrementNumbers;
let addOne = setInterval(addOneToElement.bind(this), 10);
当你绑定this
instance
您的class
的功能addOneToElement
。
问题在于内部函数addOneToElement
在 init 中创建自己的this
上下文。
一个简单的解决方法是使用没有 this 上下文的箭头函数:
class IncrementNumbers {
init() {
let target = 345;
let current = 0;
// Use an arrow function here.
const addOneToElement = () => {
if (current === target) {
clearInterval(addOne);
}
current++;
this.numberObject.innerHTML = current; <---- ERROR HERE
}
let addOne = setInterval(addOneToElement, 10);
}
}
另一种选择是将 this 上下文绑定到 addOneToElement:
let addOne = setInterval(addOneToElement.bind(this), 10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.