3

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?

2
  • put a console.log(this) inside the click event handler function (where you now have userInput). What does it tell you ? :) Commented Jul 15, 2013 at 12:42
  • Is the $ jQuery? If it is, add the tag. Commented Jul 15, 2013 at 12:43

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

What is the meaning of $this? I mean is this var that = this; different than var $that = this; ?
@x4ph4r No, there's no difference, $this is just the name of a variable, just like that.
0

the "this" inside your onclick function is referencing "this.ev" which is

"$('.' + event);" 

not your object with "userInput" and "show".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.