繁体   English   中英

将“ this”传递给函数相当于什么?

[英]What's the equivalent of passing “this” to a function?

我有一个函数希望将“ this”作为参数传递,但是我想传递一个不同的对象而不移动触发函数,所以目前我有这样的函数:

onclick="showCalendarControl(this);"

但是我想这样做:

onclick="showCalendarControl(document.getElementById('somethingelse'));"

就目前情况而言,这是行不通的,我是否正在尝试做一些不可能的事情?

尝试使用.bind()函数。 文件

bind的第一个参数将设置函数的this参数(替换默认参数),一旦调用该方法,所有其他参数都将转换为参数。

例子:

onclick="showCalendarControl.bind(this)"  //the this-statement inside of showCalendarControl will be the specified one

onclick="showCalendarControl.bind(something, this);" //this will be passed as first argument to showCalendarControl

编辑:经过测试,似乎.bind()在onclick处理程序中不起作用。 但是您的最初想法有效,或者至少是我所理解的问题(将document.getElementById结果传递给您的方法)

 function showCalendarControl(obj) { obj.innerHTML = "YEY"; } 
 <body> <div id="something" onclick="showCalendarControl(document.getElementById('somethingelse'));">Click Me</div> <div id="somethingelse"></div> </body> 

如果要将参数绑定到函数的this语句,则可以尝试以下操作(使用call()函数代替我的初始绑定):

 function showCalendarControl() { this.innerHTML = "YEY"; } 
 <body> <div id="something" onclick="showCalendarControl.call(document.getElementById('somethingelse'));">Click Me</div> <div id="somethingelse"></div> </body> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM