簡體   English   中英

誰能解釋這兩個代碼之間的區別? 又為什么第二個有效而第一個無效呢?

[英]Can anyone explain the difference between those two codes? And why does the second one work and the first doesn't?

HTML:

<input type="button" name="red" onclick="dis()">

這是JavaScript的第一個代碼:

function dis() {
  alert(this.name)
}

這是工作版本:

HTML:

  <input type="button" name="red" onclick="dis(this)">

JavaScript:

function dis(a) {
  alert(a.name)
}

在第一種情況下,您在全局范圍內調用dis() 在這種情況下, this是全局對象

在第二種情況下,您還可以在全局范圍內調用dis() 但是你通過當前this值作為參數的功能。

為了使第一種情況與第二種情況相同,您應該像這樣重寫它:

<input type="button" name="red" onclick="dis.call(this)">

通過這種方式傳遞電流this發揮作用。

一般規則是看一下函數左側的位置(換句話說-稱為函數):

dis()     // -> on the left nothing stands, so `this` will correspond to global object
a.dis()   // -> on the left `a` stands, so `this` will correspond to `a`
new dis() // -> on the left `new` keyword stands, so `this` will correspond to newly created object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM