2016-12-30 136 views
0

我已閱讀關於「this」關鍵字,並且我瞭解到「this」關鍵字適用於上下文中的對象。在JavaScript中使用「this」關鍵字

<!DOCTYPE html> 
    <html> 
    <body> 



    <form id="myForm"> 
    <label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid" required ><input type="submit"></label>                
    <div><button onclick="previewMessage()">Preview errors</button></div> 
    <div id="err"></div> 
    </form> 

    <script> 

     function checkValid() { 
      if (this.value == "fun") { 
       this.setCustomValidity("You're having too much fun!"); 
      } else { 
     // input is fine -- reset the error message 
     this.setCustomValidity(''); 
      } 
     } 
     function previewMessage() { 
      var myform = document.getElementById("noFun") 
      document.getElementById("err").innerHTML = myform.validationMessage; 
     } 
    </script> 

    </body> 
    </html> 

但是當我使用oninput =「checkValid」,它應該複製checkValid的功能和作用裏面的「this」關鍵字應指向輸入object.But這是不是這樣的!

看看這段代碼,它意味着與前一個相同,但正常運行。

<form id="myForm"> 
    <label>Type anything but "fun": <input id="noFun" type="text"   oninput="checkValid(this)" required ><input type="submit"></label> 
    <div><button onclick="previewMessage();">Preview errors</button></div> 
    <div id="err"></div> 
    </form> 
    <script> 
     function checkValid(input) { 
      if (input.value == "fun") { 
       input.setCustomValidity("You're having too much fun!"); 
      } else { 
       // input is fine -- reset the error message 
       input.setCustomValidity(''); 
      } 
     } 
     function previewMessage() { 
      var myform = document.getElementById("noFun") 
      document.getElementById("err").innerHTML=myform.validationMessage; 
     } 
    </script> 

你能解釋一下我的兩個片段,以及爲什麼預期的第一個例子不工作之間的差別。

在此先感謝!

+1

當你調用'checkValid()'時,'this'是'window'。調用它時,您必須執行類似'this.checkValid = checkValid; this.checkValid()'或稱它爲'checkValid.call(this)'。 – Siguza

+1

可能重複[「這個」關鍵字如何工作?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –

回答

1

但是,當我使用oninput =「checkValid」時,它應該複製checkValid函數,並且函數內的「this」關鍵字應指向輸入對象。

不,不應該。

內部事件屬性的值是事件處理函數的主體

的HTML oninput="checkValid"等同於JavaScript的:

reference_to_input.oninput = function (event) { 
    checkValue; 
}; 

一提的變量(如checkValue),而不做任何它(就像把()後調用一個函數)什麼都不做。

0

您設置事件處理程序的方式是這樣的:this的值將是而不是<input>元素。你有什麼相當於一個「裸體」函數調用,所以this將引用window對象。

但是,如果你要建立該事件處理程序在JavaScript這樣的:

document.getElementById("noFun").oninput = checkValid; 

你會得到this參考元素。

請注意,您的代碼將引用傳遞給元素作爲參數,這就是您的第二個代碼示例的作用原因。

+0

那麼有什麼區別 –

+0

document.getElementById (「noFun」)。oninput = checkValid; –

+0

AND