javaScript學習筆記之-------this

上篇文章----javaScript學習筆記之-------閉包 https://www.cnblogs.com/donglt-5211/p/10307973.html

在糾結的時候討論到  this,因而開始四處網羅   this  html

 

this的地道解釋:函數運行時所在的環境。java

 

1.函數調用 -- this表明全局對象閉包

var age ='19'
function this1(){
       alert(this.age)  
}    
this1();//19

 

二、對象調用:this指上級的對象app

function this2() {
  console.log(this.x);
}
debugger
var obj = {};
obj.x = 1;
obj.m = this2;

obj.m  //不加括號指的是test這個函數
obj.m() //加上括號,指的是運行test這個函數

 

三、構造函數調用函數

所謂構造函數:就是經過這個函數,能夠生成一個新的對象

function this3() {
 this.x = 1;
}
var obj = new this3();
obj.x // 1

 

四、apply()調用

apply()是函數的一個方法,做用是改變函數的調用對象,,,它的第一個參數就表示改變後的調用這個函數的對象,,所以,this指的就是第一個參數post

var x = 0;
function this4() {
 console.log(this.x);
}

var obj = {};
obj.x = 1;
obj.m = this4;
obj.m.apply() // 0
obj.m.apply(obj)//1
相關文章
相關標籤/搜索