javascript – 为什么在此代码中id为’undefined’?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 为什么在此代码中id为’undefined’?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1760字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 为什么在此代码中id为’undefined’?](/upload/InfoBanner/zyjiaocheng/760/b314ab97636d40d7b854de1d2db2cfcc.jpg)
采取以下js,警报触发,但id为’undefined’.有人可以告诉我为什么吗?如何使用参数调用LoadPage?
var arr = [];
arr.push(LoadPage);
arr[0].call(5);
function LoadPage(id) {
alert(id);
}
解决方法:
因为您使用.call方法来调用您的函数,所以您传递的第一个参数会设置此值.
所以你需要这样做:
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 );
}
编辑:为了快速概述它如何在函数中获得它的价值,考虑这个函数将以几种不同的方式调用:
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
内容总结
以上是互联网集市为您收集整理的javascript – 为什么在此代码中id为’undefined’?全部内容,希望文章能够帮你解决javascript – 为什么在此代码中id为’undefined’?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。