国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

js中this用法實例詳解

2024-05-06 16:19:22
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了js中this用法,實例分析了this指向windows、指向對象及改變this指向的相關技巧,需要的朋友可以參考下

本文實例講述了js中this用法。分享給大家供大家參考。具體如下:

1. 指向window

全局變量

 

  
  1. alert(this//返回 [object Window] 

全局函數

 

 
  1. function sayHello(){ 
  2. alert(this); 
  3. sayHello(); 

2. 指向該對象(在全局里面this指向window,在某個對象里面this指向該對象,在閉包里面this指向window)

 

 
  1. var user="the Window"
  2. var box={ 
  3. user:'the box'
  4. getThis:function(){ 
  5. return this.user; 
  6. }, 
  7. getThis2:function(){ 
  8. return function (){ 
  9. return this.user; 
  10. }; 
  11. alert(this.user);//the Window 
  12. alert(box.getThis());//the box 
  13. alert(box.getThis2()()); 
  14. //the Window (由于使用了閉包,這里的this指向window) 
  15. alert(box.getThis2().call(box)); 
  16. //the box 對象冒充(這里的this指向box對象) 

3. 用apply,call改變函數的this指向

 

 
  1. function sum(num1, num2){ 
  2. return num1+num2; 
  3. function box(num1, num2){ 
  4. return sum.apply(this, [num1, num2]); 
  5. //this 表示window的作用域 box冒充sum來執行 
  6. console.log(box(10,10)); //20 

4. new 對象

 

 
  1. function Person(){ 
  2. console.log(this//將 this 指向一個新建的空對象 
  3. var p = new Person(); 

希望本文所述對大家的javascript程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 安图县| 建宁县| 荥经县| 都兰县| 石门县| 中山市| 福州市| 治多县| 洪湖市| 陇西县| 太保市| 手游| 仙游县| 方城县| 西畴县| 常宁市| 类乌齐县| 杭锦后旗| 沁阳市| 浮山县| 荣昌县| 措勤县| 鄂温| 鄂尔多斯市| 茂名市| 河西区| 泰兴市| 夏津县| 集安市| 雅安市| 永定县| 平泉县| 博兴县| 拜泉县| 绍兴市| 禹城市| 广西| 西华县| 太保市| 中江县| 会东县|