Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is id 'undefined' in this code?

Tags:

javascript

Take the following js, the alert fires, but id is 'undefined'. Can someone tell me why? How can I invoke LoadPage with a parameter?

var arr = [];
arr.push(LoadPage);
arr[0].call(5);

function LoadPage(id) {
    alert(id);
}
like image 864
John Livermore Avatar asked Mar 21 '26 16:03

John Livermore


2 Answers

Because you're using the .call method to invoke your function, the first argument you pass sets the value of this.

So you'd need to do this instead:

arr[0].call(5); // you're setting the value of "this" in the function to "5"

function LoadPage(id) {
    alert( this );
}

If you don't need to explicitly set the value of this, but rather just want to pass an argument, then eliminate the .call part:

arr[0](5);  // now you're just passing an argument. The value of "this" in the
            //     function will be the "window" object

function LoadPage(id) {
    alert( id );
}

EDIT: To give a quick overview of how this gets its value in a function, consider this one function that will be called in several different ways:

function some_func() {
    alert( this );  // the value of "this" changes based on how it is called.
}

  // Calling it directly, "this" is the "window" object ( in browsers )
some_func();  // window


  // Calling it from an object's property, "this" will be that object
var some_obj = { foo:'bar', a_func:some_func };
some_obj.a_func();  // the object we used to reference the function


  // Calling it via the `.call` method, "this" will be that first argument
var some_obj = {foo:'bar'};
some_func.call( some_obj );  // the object referenced by some_obj


  // Calling it via the `.apply` method, "this" will be that first argument
var some_obj = {foo:'bar'};
some_func.apply( some_obj );  // the object referenced by some_obj

 // (The difference between `.call` and `.apply` is the manner in which
 //         they accept additional arguments passed to the function.)

In newer browsers, you can use .bind() to get a copy of the function that has its "this" value bound to it.

var some_obj = {foo:'bar'};
var new_func = some_func.bind( some_obj );

some_func(); // will be window
new_func();  // will be the object that we bound
like image 92
user113716 Avatar answered Mar 23 '26 05:03

user113716


The first argument to call() is the object to which the this keyword is bound.

You should do this:

arr[0].call(arr[0], 5);
like image 40
Aron Rotteveel Avatar answered Mar 23 '26 05:03

Aron Rotteveel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!