使用prototype在JavaScript中创建类
我有一个问题,我想创建一个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 //
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将适用于所有浏览器。