类在JavaScript中使用原型

Classes in JavaScript using prototype

本文关键字:原型 JavaScript 类在      更新时间:2023-09-26

我有一个问题,我想创建一个JavaScript类:

function Calculatore(txt,elements) {
    this.p= new Processor();
    this.output=txt;
    $(elements).click(this.clickHandler);   
}
Calculatore.prototype.clickHandler = function() {
var element=$(this);
// Code Here
// "this" contains the element.
// But what if I want to get the "output" var?
// I tried with Calculatore.prototype.output but no luck.
}

那么我怎么解决这个问题呢?

你可以使用jQuery的$.proxy:

function Calculatore(txt,elements) {
    this.p= new Processor();
    this.output=txt;
    $(elements).click($.proxy(this.clickHandler, this));
}
Calculatore.prototype.clickHandler = function(event) {
    var clickedElement = event.target;
    alert(this.output);
}

编辑。Jason在评论中提出了一个很好的观点。最好使用event.target,它只引用被单击的元素,而不是elements,它可能引用与选择匹配的对象数组。

您的this值有冲突。您目前无法访问实例,因为this已被设置为click处理程序中的元素。

您可以创建一个代理函数来传递this值(元素)和实例:

function Calculatore(txt,elements) {
    this.p= new Processor();
    this.output=txt;
    var inst = this; // copy instance, available as 'this' here
    $(elements).click(function(e) {
        return inst.clickHandler.call(this, e, inst); // call clickHandler with
                                                      // 'this' value and 'e'
                                                      // passed, and send 'inst'
                                                      // (the instance) as well.
                                                      // Also return the return
                                                      // value
    });
}
Calculatore.prototype.clickHandler = function(e, inst) {
    var element = $(this);
    var output = inst.output;
};