javaScript学习笔记之-------this javaScript学习笔记之-------闭包

上篇文章----javaScript学习笔记之-------闭包 https://www.cnblogs.com/donglt-5211/p/10307973.html

在纠结的时候讨论到  this,于是开始四处网罗   this  

this的地道解释:函数运行时所在的环境。

1.函数调用 -- this代表全局对象

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

2、对象调用:this指上级的对象

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

obj.m  //不加括号指的是test这个函数
obj.m() //加上括号,指的是运行test这个函数

3、构造函数调用

所谓构造函数:就是通过这个函数,可以生成一个新的对象

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

4、apply()调用

apply()是函数的一个方法,作用是改变函数的调用对象,,,它的第一个参数就表示改变后的调用这个函数的对象,,因此,this指的就是第一个参数

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

 

猜你喜欢

转载自www.cnblogs.com/donglt-5211/p/10308730.html