Newbie
Newbie

Reputation: 2825

Why this function is triggered directly instead of by click in javascript?

I have a object declare like this:

function weapon ( id, name){
    this.id = id;
    this.name = name;
    this.call; 
}

then I have created an instance of it:

someweapon = new weapon (1, 'gun');
someweapon.call = function() { //do something };

When I am creating a element:

<img src='...' onclick='someweapon.call()' />

supposingly, I will see a clickable image which I can click it to invoke the function. However, the function (someweapon.call()) is called automatically as soon as the image is shown.

Any solution to this?

Upvotes: 0

Views: 62

Answers (2)

kubetz
kubetz

Reputation: 8556

For me your code works. The .call() method is probably getting called from somewhere else.

Here is a snippet that works for me.

JavaScript:

function weapon ( id, name){
  this.id = id;
  this.name = name;
}

someweapon = new weapon (1, 'gun');
someweapon.call = function() { alert("called"); };

You don't need to this.call inside the weapon(). If you define it there it has still value undefined. You can also write this.call = function() { alert("called"); }; inside weapon() which means it will be accessible by every instance of weapon and not only by someweapon.

HTML:

<img src='http://jsfiddle.net/img/logo.png' onclick='someweapon.call()' />

EDIT: tom and Jared Farrish have a good point. call() is already defined for functions. You are defining .call() for objects and not for functions so nothing should get (theoretically) overwritten, but it is a good practice to not use names like that as it may be confusing. Rename .call() to something else.

Upvotes: 2

tom
tom

Reputation: 692

I think it has something to do with the funcktion name: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call So you might try a different one.

Upvotes: 2

Related Questions