JavaScript中的this指向

1. 全局环境下的this

在全局环境中(在浏览器中是window对象,在Node.js中是global对象),this指向全局对象。

console.log(this === window); // 在浏览器中为true 
console.log(this.document !== undefined); // true,因为this指向window,window有document属性

2. 函数调用中的this

在普通函数调用中(即非方法调用),this指向全局对象(在严格模式下thisundefined)。

function test() {  
  console.log(this === window); // 在非严格模式下为true  
}  
  
test();  
  
function strictTest() {  
  "use strict";  
  console.log(this === undefined); // 在严格模式下为true  
}  
  
strictTest();


3. 方法调用中的this

当一个函数被赋值给对象的一个属性,并作为该对象的方法被调用时,this指向该对象。

var obj = {  
  prop: 'value',  
  method: function() {  
    console.log(this.prop); // 'value',因为this指向obj  
  }  
};  
  
obj.method();

4. 构造函数中的this

在使用new关键字调用构造函数时,this指向新创建的对象实例。

function MyConstructor() {  
  this.prop = 'value';  
}  
  
var myObject = new MyConstructor();  
console.log(myObject.prop); // 'value',因为this在MyConstructor中指向了myObject


5. 使用callapplybind方法

callapply方法可以显式地设置this的值。

  • apply()把参数打包成Array再传入;

  • call()把参数按顺序传入。

比如调用Math.max(3, 5, 4),分别用apply()call()实现如下:

Math.max.apply(null, [3, 5, 4]); // 5
Math.max.call(null, 3, 5, 4); // 5

bind方法返回一个新函数,这个新函数在被调用时,其this被永久绑定为bind的第一个参数。

function greet() {  
  return "Hello, " + this.name;  
}  
  
var obj = {name: "World"};  
  
console.log(greet.call(obj)); // Hello, World  
console.log(greet.apply(obj)); // Hello, World  
  
var boundGreet = greet.bind(obj);  
console.log(boundGreet()); // Hello, World

 

6. 箭头函数中的 this

箭头函数不绑定自己的this,它会捕获其所在上下文的this值,作为自己的this值。

var obj = {  
  prop: 'value',  
  method: function() {  
    return () => this.prop; // 箭头函数中的this指向obj  
  }  
};  
  
console.log(obj.method()()); // 'value'
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值