Maximus S
Maximus S

Reputation: 11135

Simple javascript syntax

player object has a method stopVideo()

1.False

setTimeout(player.stopVideo, 1000); //says something is undefined

2.True

setTimeout(stopVideo, 1000);

function stopVideo() {
    player.stopVideo();
}

What's the difference and why is this happening?

Upvotes: -1

Views: 95

Answers (5)

simonleung
simonleung

Reputation: 44

Another reason why #1 doesnt work: when you pass player.stopVideo to setTimeout, the "this" object for the method is "window", not "player". So, probably, player.stopVideo wont works.

Upvotes: 0

simonleung
simonleung

Reputation: 44

Why 1. doesnt work. It is because player.stopVideo is not defined before setTimeout(....)

Why 2. works even player is not defined. when you declare a function stopVideo, the JS engerine will predefine this function at the begining. stopVideo function is defined before setTimeout(...). Thus it's OK.

Upvotes: 0

Vijay Verma
Vijay Verma

Reputation: 3698

Both are alias of each other. This should work:

setTimeout(player.stopVideo(), 1000);

Upvotes: 0

ivarni
ivarni

Reputation: 17878

If I open the Chrome devtools console and paste in

var player = { stopVideo: function() { console.log('ohai'); }}
setTimeout(player.stopVideo, 1000);

Nothing undefined pops up. I think you need to provide a little more context and a better explanation of what is wrong. Is your stopVideo-function trying to access this?

Upvotes: 2

Lix
Lix

Reputation: 48006

The correct signature for the setTimeout function is as follows:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
var timeoutID = window.setTimeout(code, delay);

Your second example works because you are actually defining a function within the setTimeout call.

Your first example is actually the second signature here. So for it to work, you'd have to deal with it as if it was code and pass it as a string (similar to eval() ).

setTimeout( "player.stopVideo()", 1000 );

Here is a link to the resource and an excerpt from the description of the parameters:

  • func is the function you want to execute after delay milliseconds.
  • code in the alternate syntax is a string of code you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as using eval())

Upvotes: 3

Related Questions