美文网首页
JavaScript中的this

JavaScript中的this

作者: Asher_Tan | 来源:发表于2018-05-14 23:56 被阅读6次

JavaScript中的this很容易让人迷惑,但弄清楚后其实还是很好区分的。JavaScript中的this总是指向一个对象,而具体指向哪个对象是在运行时基于函数的执行环境动态绑定的,不是函数声明时的环境。
实际能区分如下4种的情况就Ok了。

  1. 函数作为对象的属性调用时
  2. 作为普通函数时
  3. 构造器中
  4. Function.prototype.apply/call 时
    下面来分别讲讲。

作为函数属性被调用

当函数作为对象的属性(方法)被调用时,this指向该对象

const obj = {
  name: 'Asher',
  getName: function () {
    console.log(this === obj); // true
    console.log(this.name); // 输出Asher
  }
}
obj.getName();

作为普通函数调用

当函数不作为对象的属性被调用时,就是普通函数的方式,此时的this总是指向全局对象。浏览器环境更里,这个全局对象就是window对象。

window.name = 'global asher';
const getName = function () {
  console.log(this.name)
}

getName() // 输出global asher

下面情况与第一种情况会让人很迷惑
由于obj.getName方法被另外一个变量引用后再调用,此时已经是做为普通函数调用了,故this指向的是window

 window.name = 'global'
 const  obj = {
   name: 'ahser',
   getName: function () {
     console.log(this.name);
   }
 }
 const getName = obj.getName;
 getName() // 输出global

构造器

当函数使用new执行是,函数是作为构造器的,this指向的是生成的对象

const myClass = function () {
  this.name = 'Asher';
}

const obj = new myClass();
console.log(obj.name) // 输出Asher

apply & call 调用

这两种调用方式就很灵活了,可以动态的改变函数this的指向。

const obj1 = {
  name: 'Asher',
  getName: function () {
    return this.name
  }
}

const obj2 = {
  name: 'Tan'
}

console.log(obj1.getName())  // output: Asher
console.log(obj1.getName.call(obj2))  // output: Tan

掌握了这四种情况的this指向,就基本上完全理解了JavaScript的this了,不会再被迷惑this指向的是哪个对象。

相关文章

  • 1body中添加js

    1 中的 JavaScript JavaScript 函数和事件上面例子中的 JavaScript 语句,会...

  • JS中的类型转换

    JavaScript 中的类型转换 JavaScript 基本数据类型 JavaScript 中的一共有 8 中内...

  • js中的this

    javascript中的this javascript中的this与java中的this有点不同。ECMAScri...

  • JavaScript中的字符串

    @(javascript)[js字符串][toc] JavaScript中的字符串 字符串是JavaScript中...

  • 06-JavaScript数组和函数

    JavaScript数组 JavaScript中的数组可以存储不同类型的数据 JavaScript中的数组是引用类...

  • Client's JavaScript

    什么是JavaScript? JavaScript的运行环境? 浏览器中JavaScript可以做什么? 浏览器中...

  • javascript中的this

    一般说到JS的this,都会想起在函数中变来变去的this。但是事情的发生都是有规则的约束,JS中的this也不例...

  • JavaScript中的this

    什么是this? 首先对this的下个定义:this是在执行上下文创建时确定的一个在执行过程中不可更改的变量。th...

  • JavaScript中的this

    JavaScript中的this很容易让人迷惑,但弄清楚后其实还是很好区分的。JavaScript中的this总是...

  • javascript中的this

    在javascript中的this大致可以理解成谁调用的this就指向谁 全局环境中的this 函数中的this ...

网友评论

      本文标题:JavaScript中的this

      本文链接:https://www.haomeiwen.com/subject/dbpsdftx.html