以下是一段js代码,虽然alert被触发了,但id的值为“undefined”。 请问有人知道原因吗?我该如何调用LoadPage并传递参数?
var arr = [];
arr.push(LoadPage);
arr[0].call(5);
function LoadPage(id) {
alert(id);
}
以下是一段js代码,虽然alert被触发了,但id的值为“undefined”。 请问有人知道原因吗?我该如何调用LoadPage并传递参数?
var arr = [];
arr.push(LoadPage);
arr[0].call(5);
function LoadPage(id) {
alert(id);
}
.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
call()
的第一个参数是绑定this
关键字的对象。arr[0].call(arr[0], 5);
this
的值,例如arr[0](5)
,只需删除.call
。您几乎总是从对函数的引用中调用函数。只是函数内部的this
值根据调用方式而改变。 - user113716