Victor
Victor

Reputation: 22198

How forward the 'this' scope to a function call in javascript

How can I forward the this scope refering to a element that is calling event listener?

exemple:

<input type=button value="Foo" id=mybutton>

addEvent('mybutton','touchstart', function(){
    if(window['touchmoved']==false)
    hover(); 
});


function hover(){
    this.value //undefined
}

Upvotes: 2

Views: 638

Answers (3)

Stuart.Sklinar
Stuart.Sklinar

Reputation: 3761

You could use the function.Call() method on your hover() method which will call the hover method.

the Call method's first parameter is a value which should be assigned to this in the calling method.

for instance:

addEvent('mybutton','touchstart', function(){
if(window['touchmoved']==false)
{

}
    hover.call(this); 
});


function hover(){
    //this = touchstart event
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 708056

Use fn.call() or fn.apply() to set what you want the value of this to be. See references for call or apply at MDN.

addEvent('mybutton','touchstart', function(){
    if(window['touchmoved']==false) {
        hover.call(this); 
    }
});

Both .call() and .apply() allow you to specify what you want the this pointer to be in the called function.

.call() lets you pass specific additional arguments that you want the called function to receive like this:

fn.call(this, true, "foo")`

.apply() is used when the arguments you want to pass to the called function are in an array and you just pass the array of arguments like this:

var args = [true, "foo"];
fn.apply(this, args);

.apply() is often used with the built-in arguments object to pass the existing arguments on to the called function (though there are other reasons to use it too):

fn.apply(this, arguments);

Upvotes: 3

Rob W
Rob W

Reputation: 349232

Use the JavaScript Function.call or Function.apply methods:

addEvent('mybutton','touchstart', function(){
    if(window['touchmoved']==false)
        hover.call(this); // `this` of the called hover points to this `this`
});

Upvotes: 7

Related Questions