user3609223
user3609223

Reputation: 3

TypeError: undefined is not a function in javascript

Hey guys am new to javascript and when i tried some piece of code its showing type error ..The code is

var something = function(element){
    this.name = "oops";
    this.some = function(element) { console.log(this.name); }; 
    element.addEventListner('click', this.some, false); 
}

When i called the above function like var b = something("baba"); its showing error TypeError: undefined is not a function..I dunno why it happens like this..

Hope you can help me ..Thanks

Upvotes: 0

Views: 105

Answers (3)

sebagomez
sebagomez

Reputation: 9599

First of all, fix the typo mentioned by @Sushanth

Make sure you bind the function to the object you want the some function to have as this.

Here's what the coude should look like:

var something = function(element){
    this.name = "oops";
    this.some = function(element) { console.log(this.name); }; 
    element.addEventListener('click', this.some.bind(this), false); 
}

See it working here: http://jsfiddle.net/y2BPm/1/

Edit: The function you added to this.some could be anything and will have no idea what you meant by using this, unless you actually tell it "bind it" to an object, in which case this inside the function will be whatever you binded it to. In this case, the something function

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

First addEventListner should be addEventListener

Next You are binding a click event to the element in question.

Where as you seem to be passing in a string and then binding the event to it. (make sure the argument you pass in is a valid object to which events can be bound to).

The context of this inside the function will be the window object. So you would need to bind the context to the event.

var something = function(element){
    this.name = "oops";
    this.some = function(element) { console.log(this.name); }; 
    element.addEventListener('click', this.some.bind(this), false); 
}

var elem = document.getElementById('elem'); 

var b = something(elem);

Check Fiddle

Upvotes: 2

Johney
Johney

Reputation: 87

Continuing to First addEventListner should be addEventListener

Consider only below thing:

var b = something("baba");

here "baba" is a string. Your function is expecting an element.

eg.

   var something = function (element) {
            this.name = "oops";
            this.some = function (element) { console.log(this.name); };
            element.addEventListener('click', this.some, false);
        }   




<input type="button" value="click here" onclick="something(this);" name="TestName" />     

Above code should work....

Upvotes: 0

Related Questions