簡體   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