Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用prototype在JavaScript中创建类_Javascript_Jquery - Fatal编程技术网

使用prototype在JavaScript中创建类

使用prototype在JavaScript中创建类,javascript,jquery,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 //

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

}

那么我该如何解决这个问题呢?

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

您可以使用代理函数来传递
值(元素)和实例:

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;
};

您可以使用jQuery的
$。代理

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);
}

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

或使用
event.target
而不是保存元素(event是clickHandler中的第一个参数)。请注意,event.target(这是W3C规范)与IE不兼容-您还必须检查event.srcElement。@MikeChristensen,因为OP使用的是jQuery,所以检查由库处理。因此event.target将适用于所有浏览器。