JavaScript this

this


系列文章

这是JavaScript系列文章:



简述

全局执行环境中(在任何函数体外部)this 都指向全局对象。
在函数内部,this的值取决于函数被调用的方式。

this 更像是一个指向当前运行函数的“桥梁”(可能比喻的不是很准确),它可以链接当前运行环境,以便获取运行环境里面的一些变量、函数等。

原理

参照阮一峰老师的图,我也整一个:

  1. 全局this
    全局this
  2. 函数内this
    函数内this

使用环境

全局

// 在浏览器中,window 对象同时也是全局对象
console.log(this === window);  // true

a = 32;
console.log(window.a);  // 32
console.log(this.a);  // 32
console.log(a);  // 32

this.b = "test";
console.log(window.b);  // "test"
console.log(b);  // "test"

函数

简单调用
  1. 严格模式
    在严格模式下,如果 this 没有被执行环境(execution context)定义,那它将保持为 undefined。

    function f2(){
      "use strict"; // 这里是严格模式
      return this;
    }
    
    f2() === undefined; // true
    
  2. apply / call

    • this 的环境换到另一个环境
    • 使用 call 和 apply 函数的时候要注意,如果传递给 this 的值不是一个对象,JavaScript 会尝试使用内部 ToObject 操作将其转换为对象。因此,如果传递的值是一个原始值比如 7 或 ‘foo’,那么就会使用相关构造函数将它转换为对象,所以原始值 7 会被转换为对象,像 new Number(7) 这样,而字符串 ‘foo’ 转化成 new String(‘foo’) 这样
    // 将一个对象作为call和apply的第一个参数,this会被绑定到这个对象。
    var obj = { a: 'Custom' };
    
    // 这个属性是在global对象定义的。
    var a = 'Global';
    
    function whatsThis(arg) {
      return this.a;  // this的值取决于函数的调用方式
    }
    
    whatsThis();          // 'Global'
    whatsThis.call(obj);  // 'Custom'
    whatsThis.apply(obj); // 'Custom'
    
    function add(c, d) {
      return this.a + this.b + c + d;
    }
    
    var o = {a: 1, b: 3};
    
    // 第一个参数是作为‘this’使用的对象
    // 后续参数作为参数传递给函数调用
    add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
    
    // 第一个参数也是作为‘this’使用的对象
    // 第二个参数是一个数组,数组里的元素用作函数调用中的参数
    add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
    
bind方法

调用f.bind(someObject)会创建一个与f具有相同函数体和作用域的函数,但是在这个新函数中,this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var h = g.bind({a:'yoo'}); // bind只生效一次!
console.log(h()); // azerty

var o = {a:37, f:f, g:g, h:h};
console.log(o.f(), o.g(), o.h()); // 37, azerty, azerty
箭头函数

在箭头函数中,this与封闭词法环境的this保持一致。在全局代码中,它将被设置为全局对象

var globalObject = this;
var foo = (() => this);
console.log(foo() === globalObject); // true

// > 注意:如果将this传递给call、bind、或者apply,它将被忽略。不过你仍然可以为调用添加参数,不过第一个参数(thisArg)应该设置为null。

// 接着上面的代码
// 作为对象的一个方法调用
var obj = {foo: foo};
console.log(obj.foo() === globalObject); // true

// 尝试使用call来设定this
console.log(foo.call(obj) === globalObject); // true

// 尝试使用bind来设定this
foo = foo.bind(obj);
console.log(foo() === globalObject); // true
作为对象的方法

this 是调用该函数的对象

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

不受函数位置和定义方式影响

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37
  • 原型链的this

    var o = {
      f: function() { 
        return this.a + this.b; 
      }
    };
    var p = Object.create(o);
    p.a = 1;
    p.b = 4;
    
    console.log(p.f()); // 5
    
  • getter 与 setter 中的 this

    function sum() {
      return this.a + this.b + this.c;
    }
    
    var o = {
      a: 1,
      b: 2,
      c: 3,
      get average() {
        return (this.a + this.b + this.c) / 3;
      }
    };
    
    Object.defineProperty(o, 'sum', {
        get: sum, enumerable: true, configurable: true});
    
    console.log(o.average, o.sum); // logs 2, 6
    
作为构造函数

this 被绑定到正在构造的新对象。

/*
 * 构造函数这样工作:
 *
 * function MyConstructor(){
 *   // 函数实体写在这里
 *   // 根据需要在this上创建属性,然后赋值给它们,比如:
 *   this.fum = "nom";
 *   // 等等...
 *
 *   // 如果函数具有返回对象的return语句,
 *   // 则该对象将是 new 表达式的结果。 
 *   // 否则,表达式的结果是当前绑定到 this 的对象。
 *   //(即通常看到的常见情况)。
 * }
 */

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;  // 因为后面有return语句,所以这条语句执行是执行了,但是对外部环境无影响
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38

参考链接

[1] 阮一峰. Javascript 的 this 用法
[2] 阮一峰. JavaScript 的 this 原理
[3] MDN. this

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值