请参阅以下代码:
class game{
constructor(){
this.a = 'Helloword';
this.add_event();
}
add_event(){
clicked = function(){
console.log(this.a); // I want to print hellowowrd
}
let i = document.getElementById('aDiv'); //just a div
i.addEventListener('click',clicked);
}}
正如您所看到的,在单击的函数中,这指的是div,而不是类,但我想从' this.a
&#39;打印HelloWorld,我该怎么做。< / p>
答案 0 :(得分:1)
您需要将this
保留为self
add_event() {
var self = this;
let i = document.getElementById('aDiv');
i.addEventListener('click', function() { //notice that function given as an argument diretly
console.log(self.a); // I want to print hellowowrd
} );
}
<强>演示强>
class game {
constructor() {
this.a = 'Helloword';
this.add_event();
}
add_event() {
var self = this;
let i = document.getElementById('aDiv'); // just a div
i.addEventListener('click', function() {
console.log(self.a); // I want to print hellowowrd
} );
}
}
console.log( new game() )
&#13;
<div id="aDiv">aDiv</div>
&#13;
答案 1 :(得分:0)
尝试使用self = this
class game{
constructor(){
this.a = 'Helloword';
this.add_event();
}
add_event(){
var self = this
clicked = function(){
console.log(self.a); // I want to print hellowowrd
}
let i = document.getElementById('aDiv'); //just a div
i.addEventListener('click',clicked);
}}
或者我猜你可以使用胖箭头语法
clicked (()=>{
console.log(this.a);
})
我认为这样可行。
答案 2 :(得分:0)
只需点击箭头功能:
add_event(){
const clicked = () =>{
console.log(this.a); // It prints hellowowrd
};
}