为什么这段代码中ID为“undefined”?

3

以下是一段js代码,虽然alert被触发了,但id的值为“undefined”。 请问有人知道原因吗?我该如何调用LoadPage并传递参数?

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

function LoadPage(id) {
    alert(id);
}
4个回答

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

谢谢,如果我只有对该函数的引用(不确定“引用”在这里是否正确),是否有其他调用该函数的方法? - John Livermore
4
如果您不需要显式设置 this 的值,例如 arr[0](5),只需删除 .call。您几乎总是从对函数的引用中调用函数。只是函数内部的 this 值根据调用方式而改变。 - user113716
2
@John 你有两个选项可以使用call()和apply(),它们非常相似,只是在如何处理参数上有所区别。两者都需要一个作用域/上下文(即应该在方法调用中被视为'this'的对象)。 - Matt

3
call()的第一个参数是绑定this关键字的对象。
你应该这样做:
arr[0].call(arr[0], 5);

2

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

arr[0](5);

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

2

来自MDC文档

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

您传递的第一个参数成为“this”的值。第二个参数是第一个实际参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接