为什么在此代码中id为'undefined'?

时间:2011-05-18 14:19:02

标签: javascript

采取以下js,警报触发,但id为'undefined'。有人可以告诉我为什么吗?如何使用参数调用LoadPage?

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

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

4 个答案:

答案 0 :(得分:5)

因为您正在使用.call方法来调用您的函数,所以您传递的第一个参数会设置this的值。

所以你需要这样做:

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

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

如果您不需要显式设置this的值,而只是想传递一个参数,那么就消除.call部分:

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 );
}

编辑:要快速了解this如何在函数中获取其值,请考虑以下几种方式调用此函数:

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.)

在较新的浏览器中,您可以使用.bind()获取与其“this”值绑定的函数的副本。

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

答案 1 :(得分:3)

call()的第一个参数是this关键字绑定的对象。

你应该这样做:

arr[0].call(arr[0], 5);

答案 2 :(得分:2)

来自MDC docs

fun.call(thisArg[, arg1[, arg2[, ...]]])

你传递的第一个参数是“this”的值。第二个是第一个真实参数。

答案 3 :(得分:2)

使用.call()设置函数中this的值。尝试以这种方式调用函数:

arr[0](5);

演示:http://jsfiddle.net/6D8wN/