使用原型的JavaScript中的类

eli*_*264 5 javascript jquery

我有一个问题,我想创建一个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.

}
Run Code Online (Sandbox Code Playgroud)

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

pim*_*vdb 3

你们的价值观之间存在冲突this。您当前无权访问该实例,因为this已设置为单击处理程序内的元素。

您可以创建一个代理函数来传递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;
};
Run Code Online (Sandbox Code Playgroud)