[英]object has not method error in javascript
I am using following code but it returns following error 我正在使用以下代码,但它返回以下错误
Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'userInput'
Here is the code jsfiddle 这是代码jsfiddle
var ClickEvent = function (event) {
this.ev = $('.' + event);
this.ev.on('click', function () { this.userInput(); });
};
ClickEvent.prototype = function () {
return {
userInput: function () {
console.log('user');
},
show: function () {
console.log('show');
}
};
}();
var c = new ClickEvent('event');
I am calling userInput
function inside on()
callback function but it returns above error
. 我在
on()
回调函数中调用userInput
函数on()
但它返回上面的error
。
How can I solve this problem? 我怎么解决这个问题?
The problem is the execution context( this
) inside the click callback handler does not point to the ClickEvent
instance, it is referencing the dom element that was clicked. 问题是单击回调处理程序中的执行上下文(
this
)没有指向ClickEvent
实例,它引用了被单击的dom元素。
You need to use 你需要使用
this.ev.on('click', $.proxy(function () { this.userInput(); }, this));
or 要么
var that = this;
this.ev.on('click', function () { that.userInput(); });
this.userInput()
is nested within the callback function, and thus is scoped within it. this.userInput()
嵌套在回调函数中,因此在其中作用域。 You could externalize the this
instance you need as follow: 您可以将您需要的
this
实例外部化,如下所示:
var ClickEvent = function (event) {
var $this = this;
$this.ev = $('.' + event);
$this.ev.on('click', function () { $this.userInput(); });
};
the "this"
inside your onclick
function is referencing "this.ev"
which is 在
"this"
你里面onclick
函数引用"this.ev"
这是
"$('.' + event);"
not your object with "userInput"
and "show"
. 不是
"userInput"
和"show"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.