[英]What's the equivalent of passing “this” to a function?
I have a function which is expecting "this" to be passed as a parameter but I would like to pass a different object without moving the trigger function, so currently I have this: 我有一个函数希望将“ this”作为参数传递,但是我想传递一个不同的对象而不移动触发函数,所以目前我有这样的函数:
onclick="showCalendarControl(this);"
but instead I would like to do this: 但是我想这样做:
onclick="showCalendarControl(document.getElementById('somethingelse'));"
This doesn't work as it stands, am I trying to do something impossible? 就目前情况而言,这是行不通的,我是否正在尝试做一些不可能的事情?
Try using the .bind()
function. 尝试使用
.bind()
函数。 Docs 文件
The first argument to bind
will set the functions' this
argument (replacing the default one), all other arguments are translated into parameters once the method is called. 要
bind
的第一个参数将设置函数的this
参数(替换默认参数),一旦调用该方法,所有其他参数都将转换为参数。
Examples: 例子:
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
Edit: After testing it out, it seems that .bind()
doesn't work in the onclick handler. 编辑:经过测试,似乎
.bind()
在onclick处理程序中不起作用。 But your initial idea worked, or at least what I understood as your problem (passing document.getElementById
result to your method) 但是您的最初想法有效,或者至少是我所理解的问题(将
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>
If you want to bind the parameter to the function's this
statement, you can try this (use of the call() function instead of my initial bind): 如果要将参数绑定到函数的
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.