Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

How can I solve this problem?

like image 562
Om3ga Avatar asked Mar 21 '26 19:03

Om3ga


2 Answers

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.

You need to use

this.ev.on('click', $.proxy(function () { this.userInput(); }, this));

Demo: Fiddle

or

var that = this;
this.ev.on('click', function () { that.userInput(); });

Demo: Fiddle

like image 176
Arun P Johny Avatar answered Mar 23 '26 07:03

Arun P Johny


this.userInput() is nested within the callback function, and thus is scoped within it. You could externalize the this instance you need as follow:

var ClickEvent = function (event) {
    var $this = this;
    $this.ev = $('.' + event);
    $this.ev.on('click', function () { $this.userInput(); });
};
like image 43
sp00m Avatar answered Mar 23 '26 08:03

sp00m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!