why is id 'undefined' in this code?
Take the following js, the alert fires, but id is 'undefi开发者_如何学Goned'. 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);
}
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
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);
From the MDC docs:
fun.call(thisArg[, arg1[, arg2[, ...]]])
The first argument you pass is what becomes the value of "this." The second one is the first real parameter.
Using .call()
sets the value of this
in the function. Try calling the function this way:
arr[0](5);
Demo: http://jsfiddle.net/6D8wN/
精彩评论