久久九九国产无码高清_人人做人人澡人人人爽_日本一区二区三区中文字幕_日韩无码性爱免费

JavaScript中this的用法步驟

時間:2024-10-31 11:39:51 JavaScript 我要投稿
  • 相關推薦

JavaScript中this的用法步驟

  關于JavaScript中this的用法網(wǎng)絡中已經(jīng)有較多比較詳盡的介紹,可以參考本文的參考學習資料和網(wǎng)絡。本文結(jié)合網(wǎng)絡收集整理,嘗試以一種簡易的方式闡述JavaScript中this的用法,希望對大家關于JavaScript中this用法的快速理解有所幫助。

  1. this用法實例

  復制代碼 代碼如下:

  window.color = “red”;

  var o = { color: “blue” };

  function sayColor(){

  alert(this.color);

  }

  sayColor(); //”red”

  o.sayColor = sayColor;

  o.sayColor(); //”blue”

  2. this用法簡易理解

  this指向哪里:

  this運行的環(huán)境(the context object),或者簡單理解為:this所在函數(shù)被調(diào)用時的當前作用域。

  一段實例代碼立刻明白:

  復制代碼 代碼如下:

  var fun = function() {

  console.log(this);

  }

  fun();// console: window,fun 的執(zhí)行context為window,即this所在函數(shù)(fun())被調(diào)用時的當前作用域為window。

  new fun();//console: fun,fun 的執(zhí)行context為fun對象內(nèi),即this所在函數(shù)(fun())被調(diào)用時的當前作用域為fun對象內(nèi)。

  3. this用法的一個特殊情況

 。1)情況:

  復制代碼 代碼如下:

  function demo() {

  this.value = Math.random();

  }

  點擊這個button之后,你會發(fā)現(xiàn)按鈕的value值沒有改變。

  原因:在本代碼運行的情況下this指向的是window對象。

  復制代碼 代碼如下:

  var button = document.getElementById("aButton");

  function demo() {

  this.value = Math.random();

  }

  button.onclick= demo;

  點擊這個button之后,程序可正常執(zhí)行。

 。2)原因解釋:

  復制代碼 代碼如下:

  var button = document.getElementById("aButton");

  function demo() {

  this.value = Math.random();

  }

  button.onclick= demo;

  alert(button.onclick);

  得到的輸出是:

  復制代碼 代碼如下:

  function demo() {

  this.value = Math.random();

  }

  復制代碼 代碼如下:

  var button = document.getElementById("aButton");

  function demo() {

  this.value = Math.random();

  }

  alert(button.onclick);

  得到的輸出是:

  復制代碼 代碼如下:

  function onclick() {

  demo();

  }

【JavaScript中this的用法步驟】相關文章:

Javascript中typeof 用法歸納09-27

Javascript的this用法簡述08-15

Javascript函數(shù)的定義和用法分析08-15

javascript分析運算符用法08-07

JavaScript中的with關鍵字07-24

在Java中執(zhí)行JavaScript代碼07-14

JavaScript中常見的字符串操作函數(shù)及用法07-24

抽象語法樹在JavaScript中的應用08-18

JavaScript中的三種對象10-24

perl- javascript中class的機制05-03