我是 JavaScript 类(class)的新手。我有一个 JavaScript 类。我想要的是在console.log中将输出类对象的结果而不是这个元素(mousedown的元素)。我该怎么写呢?
function Transformer (output) {
this.output = output;
$(output+' .object').mousedown(function(e){
console.log(this);
});
}
var test = new Transformer('.console');
最佳答案
如果要打印类对象本身,则需要在另一个变量中保存对上下文的引用,因为匿名函数中的 this
指向匿名函数本身的上下文:
function Transformer (output) {
var self = this;
this.output = output;
$(output+' .object').mousedown(function(e){
console.log(self); // will print the object itself
});
}
或者,您可以使用arrow function完全跳过保存引用:
function Transformer (output) {
this.output = output;
$(output+' .object').mousedown(e => {
console.log(this); // will print the object itself
});
}
关于类中的 JavaScript 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751103/