gpt4 book ai didi

类中的 JavaScript 事件

转载 作者:行者123 更新时间:2023-11-28 14:36:12 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com