JavaScript this 详解

this 是 Javascript语言 的一个关键字,它代表函数运行时自动生成的一个内部对象,只能在函数内部使用。必须要说的是 this 指向不是在函数定义时确定的,只有函数执行的时候才能确定,实际上 this 最终指向那个调用它的对象
function identify() {
  return this.name.toUpperCase();
}
function sayHello() {
  var greeting = "Hello, I'm " + identify.call(this);
  console.log( greeting );
}
var person1= {
  name: "Kyle"
};
var person2= {
  name: "Reader"
};
identify.call( person1);// KYLE
identify.call( person2);// READER
sayHello.call( person1);// Hello, I'm KYLE
sayHello.call( person2);// Hello, I'm READER

this 最终指向的是调用它的对象,下面函数a实际是被Window对象点出来的
function a(){
  var user = "名称";
  console.log(this.user); // undefined
  console.log(this); // Window
}
a(); // 等同于  window.a();

函数可以作为某个对象的方法调用,这时方法中的 this 就指这个上级对象
var o = {
  user: "名称",
  fn: function(){
    console.log(this.user); // 名称
  }
}
o.fn();

var o = {
  a: 10,
  b: {
    a: 12,
    fn: function(){
      console.log(this.a); // 12
    }
  }
}
o.b.fn();

var o = {
  a:10,
  b:{
    fn:function(){
      console.log(this.a); // undefined
    }
  }
}
o.b.fn();
注 : this 指向在函数创建的时候是决定不了,在调用的时候才能决定,谁调用的就指向谁

1> 如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,需要说明的是在严格模式下 此时就不指向 window
2> 如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象
3> 如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象

this 永远指向的是最后调用它的对象,也就是看它执行的时候是谁调用的
var o = {
  a: 10,
  b: {
    a: 12,
    fn: function(){
      console.log(this.a);// undefined
      console.log(this);// window
    }
  }
}
var j = o.b.fn;
j();// 这里将 o.b.fn方法赋给j变量,此时j变量相当于window对象的一个属性,因此 j() 执行的时候相当于 window.j(),即 window对象调用 j 这个方法,所以this关键字指向 window

var personA = {
    name: "AAA",
    showName: function(){
        console.log(this.name);// BBB
    }
}
var personB = {
    name: "BBB",
    sayName: personA.showName
}    
personB.sayName();// 虽然 showName方法是在 personA这个对象中定义,但是调用的时候却是在 personB这个对象中调用,因此 this对象指向 personB

var point = {
  x: 0,
  y: 0,
  moveTo: function(x, y) {
    var moveX = function(x) {
      this.x = x;
    };
    var moveY = function(y) {
      this.y = y;
    };
    moveX(x);
    moveY(y);
  }
};
point.moveTo(1, 1);
point.x;// 0
point.y;// 0
x;// 1
y;// 1
上面代码中 this绑定到 window的,所以改变 x 和 y的值而不是对象中的 point.x和 point.y的值,这属于 JavaScript 设计缺陷,正确的设计方式是内部函数 this 应该绑定到其外层函数对应的对象上,为了规避这一设计缺陷,使用如下替代方案 :
var point = {
  x: 0,
  y: 0,
  moveTo: function(x, y) {
    var that = this;
    var moveX = function(x) {
      that.x = x;
    };
    var moveY = function(y) {
      that.y = y;
    };
    moveX(x);
    moveY(y);
  }
};
point.moveTo(1, 1);
point.x;// 1
point.y;// 1

new关键字 可以改变 this 的指向,将这个 this指向创建对象,另外改变 this 的指向还有 apply() call() bind() 方法,apply() call()
var x = 0;
function test(){
  console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m.apply();// 0 apply()的参数为空时默认调用全局对象,这时的运行结果为0证明this指的是全局对象
o.m.apply(o);// 1 此时方法中的 this 指向 o

在使用 new 创建对象时,如果又返回值,this指向的就是那个返回的对象,如果返回值不是一个对象,那么 this 还是指向函数的实例,比较特殊的是返回 null 时this 还是指向函数的实例
function fn() {
  this.user = '名称';
  return {};
}
var a = new fn;
console.log(a.user);// undefined


function fn() {
  this.user = '名称';
  return function() {};
}
var a = new fn;
console.log(a.user);// undefined


function fn() {
  this.user = '名称';
  return 1;
}
var a = new fn;
console.log(a.user);// 名称


function fn() {
  this.user = '名称';
  return undefined;
}
var a = new fn;
console.log(a.user);// 名称


function fn() {
  this.user = '名称';
  return null;
}
var a = new fn;
console.log(a.user);// 名称

bind() 创建一个永恒的上下文链并且不可修改,一个绑定函数即使使用 .call() 或 .apply() 传入其他不同的上下文环境也不会更改它之前连接的上下文环境,重新绑定也不会起任何作用,只有在构造器调用时,绑定函数可以改变上下文,然而这并不是推荐的做法

超时调用的代码都是在全局作用域中执行的,因此函数中的 this 值,在非严格模式下是指向 window对象,在严格模式下是指向undefined,因此 setTimeout/setInterval/匿名函数 执行的时候 this默认指向 window对象,除非手动改变 this的指向
var name = "XL";
function Person() {
  this.name = "xl";
  this.showName = function() {
    console.log(this.name);// XL  setTimeout 方法中的 this 指向 window 对象
  };
  setTimeout(this.showName, 50);// 在setTimeout(this.showName,50)语句中,会延时执行 this.showName方法
}
var person = new Person();
// 更改后
var name = "XL";
function Person() {
  this.name = "xl";
  var that = this;// 让 that 得到执行 Person 实例的 this
  this.showName = function() {
    console.log(that.name);// xl
  };
  setTimeout(this.showName, 50);
}
var person = new Person();


//  匿名函数
var name = "XL";
var person = {
  name: "xl",
  showName: function(){
    console.log(this.name);// 匿名函数中的 this 指向 windows 对象
  },
  sayName: function(){
    (function(callback){
      callback();
    })(this.showName)
  };
}
person.sayName();// XL
// 更改后
var name="XL";
var person = {
  name: "xl",
  showName: function() {
    console.log(this.name);// xl
  },
  sayName: function(){
    var that = this;
    (function(callback){
      callback();
    })(that.showName);
  }
}
person.sayName();// 匿名函数的执行同样在默认情况下this是指向window的,除非手动改变this的绑定对象

eval() : 接收原始字符串,并执行其中的 JavaScript 代码,该函数执行的时候,this 绑定到当前作用域的对象上
var name = "XL";
var person = {
  name: "xl",
  showName: function(){
    eval("console.log(this.name)");
  }
}
person.showName(); //  xl
var a = person.showName;
a(); //  XL

ES6 里面 this指向固定化,始终指向外部对象,因为箭头函数没有this,因此它自身不能进行new实例化,同时也不能使用call/apply/bind等方法来改变this的指向,箭头函数一次绑定上下文后便不可更改,即使使用了上下文更改的方法 :
function Timer() {
  this.seconds = 0;
  setInterval(() => this.seconds++, 1000);
}
var timer = new Timer();
setTimeout(() => console.log(timer.seconds), 3100);// 3

// 相当于
function Timer() {
  this.seconds = 0;
  _this = this;
  setInterval(function() {
     _this .seconds++;
  }, 1000);
}
var timer = new Timer();
setTimeout(() => console.log(timer.seconds), 3100);// 3

在严格模式中的默认 this 不是 window 而是 undefined


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值