this

140 阅读2分钟

因此,提升表现力的关键,是找到自己表现力最好的状态,并将它强化,贯穿到整个面试过程中。

本节任务

理解: 理解下面的这段内容,达到熟悉的程度

JSthis指向取决于环境。

全局环境中的this,直接指向全局对象。

函数环境中的this,取决于函数如何被调用:

  1. 如果函数是直接调用的,同时又是出于严格模式下,则指向undefined,如果不是严格模式,则指向全局对象
  2. 如果函数是通过一个对象调用的,则指向对象本身
  3. 如果函数是通过一些特殊方法调用的,比如callapplybind,通过这些方法调用的话,则指向指定的对象
  4. 如果函数是通过new调用的,则指向新的实例。
  5. 另外,箭头函数由于没有this,所以箭头函数内部的this由其外部作用域决定。

普通函数

function say() {
 console.log("我的家乡在", this.name);
}

window.name = "中国";
say(); // 我的家乡在中国
function f1() {
  var name = '北京'
  function f2() {
    console.log(this)
  }
  f2()
}
f1()

对象属性

function say() {
  console.log("我的住", this.name);
}
var bj = {
  name: "北京",
  say,
  say2: () => say2()
  chaoyang: {
    name: "朝阳",
    say,
  },
};
bj.say(); // 我的住北京
bj.say2(); // 我的住undefind
bj.chaoyang.say(); // 我的住朝阳

构造函数与Class

function say() {
  console.log("我的家乡:", this.name);
}
function Country(name) {
  this.name = name
}
Country.prototype.say = say
const china = new Country('中国')
china.say()

call、apply、bind方法中

function say() {
  console.log('我的家乡:' + this.name)
}
window.name = '中国'
say()
say.apply({name : '北京'})
say.call({name : '朝阳'})
var mySay = say.bind({name: '曹县'})
mySay()

严格模式下this

  • 函数外指向window
  • 函数中是undefined
"use strict"
console.log(this) // window
function foo() {
  console.log(this) // undefined
}
foo()

箭头函数

// 箭头函数没有this
// 箭头函数没有 arguments
// 
function say() {
  console.log("我的家乡在"+this.name);
}
var bj = {
  name: "北京",
  say: () => say(),
  chaoyang: {
    name: "朝阳",
    say : () => say(), // 箭头函数
  },
};
windown.name = '中国'
bj.say(); // 我的家乡在中国
bj.chaoyang.say(); // 我的家乡在中国

Dom事件

在Dom事件会回调里,this指向绑定事件对象

<html>
    <button id='1'>1</button>
    <button id='2'>2</button>
    <script>
        function fn() {
            console.log(this)
        }
        document.getElementById('1').addEventListener('click',fn)
        document.getElementById('2').addEventListener('click',fn)
    </script>
</html>