【JavaScript】避免this指向window的解决方法

本文探讨JavaScript中this的关键字使用,涉及多层this处理、严格模式下的错误、数组操作函数中的this绑定,以及通过call/apply/bind控制this指向。实例演示了如何避免常见的this问题,确保正确执行。
摘要由CSDN通过智能技术生成

传送门:JavaScript 教程 / 面向对象编程 / this 关键字 / 4. 使用注意点


1. 【多层this】this赋值给一个变量

  • 未处理:
var o = {
  f1: function () {
    console.log(this);	// Object
    var f2 = function () {
      console.log(this);	// Window
    }();
  }
}

o.f1();
  • 处理后:
var o = {
  f1: function () {
    console.log(this);	// Object
    
    var that = this;	// this 指向当层环境
    
    var f2 = function () {
      console.log(that);	// Object
    }();
  }
}

o.f1();

应用场景:forEach、map【数组处理函数】(另一种解决方法在第三点)

  • 未处理:
var o = {
  v: 'hello',
  p: [ 'a1', 'a2' ],
  f: function f() {
    this.p.forEach(function (item) {
      console.log(this.v + ' ' + item);
    });
  }
}

o.f();
// undefined a1
// undefined a2
  • 处理后:
var o = {
  v: 'hello',
  p: [ 'a1', 'a2' ],
  f: function f() {
    var that = this;
    this.p.forEach(function (item) {
      console.log(that.v+' '+item);
    });
  }
}

o.f();
// hello a1
// hello a2

2. 【严格模式】this指向顶层对象则报错

  • 未处理:
var counter = {
  count: 0
};
counter.inc = function () {
  this.count++;
};
var f = counter.inc;

f();	// undefined
  • 处理后:
var counter = {
  count: 0
};
counter.inc = function () {
  'use strict';
  this.count++;
};
var f = counter.inc;

f();	// Error: ...

3. 【数组处理方法】forEach、map使用第二参数传入this

  • 未处理:
var o = {
  v: 'hello',
  p: [ 'a1', 'a2' ],
  f: function f() {
    this.p.forEach(function (item) {
      console.log(this.v + ' ' + item);
    });
  }
}

o.f();
// undefined a1
// undefined a2
  • 处理后:
var o = {
  v: 'hello',
  p: [ 'a1', 'a2' ],
  f: function f() {
    this.p.forEach(function (item) {
      console.log(this.v + ' ' + item);
    }, this);	// 使用第二参数,传入this
  }
}

o.f();
// hello a1
// hello a2

4. 【上下文调用】通过call / apply / bind 来绑定 this

var obj = {};

var f = function () {
  return this;
};

f() === window // true
f.call(obj) === obj // true
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值