JavaScript 中的 this

兜兜转转绕晕我的 this

# 全局上下文

非严格模式和严格模式中this都是指向顶层对象(浏览器中是window)。

this === window // true
'use strict'
this === window;
this.name = '若川';
console.log(this.name); // 若川
1
2
3
4
5

# 函数上下文

# 普通函数调用模式

// 非严格模式
var name = 'window';
var doSth = function(){
    console.log(this.name);
}
doSth(); // 'window'
1
2
3
4
5
6
// 非严格模式
let name2 = 'window2';
let doSth2 = function(){
    console.log(this === window);
    console.log(this.name2);
}
doSth2() // true, undefined
1
2
3
4
5
6
7

这个例子中let没有给顶层对象中(浏览器是window)添加属性,window.name2和window.doSth都是undefined。

严格模式中,普通函数中的this则表现不同,表现为undefined。

// 严格模式
'use strict'
var name = 'window';
var doSth = function(){
    console.log(typeof this === 'undefined');
    console.log(this.name);
}
doSth(); // true,// 报错,因为this是undefined
1
2
3
4
5
6
7
8

# 对象中的函数(方法)调用模式

var name = 'window';
var doSth = function(){
    console.log(this.name);
}
var student = {
    name: 'wudeh',
    doSth: doSth,
    other: {
        name: 'other',
        doSth: doSth,
    }
}
student.doSth(); // 'wudeh'
student.other.doSth(); // 'other'
// 用call类比则为:
student.doSth.call(student);
// 用call类比则为:
student.other.doSth.call(student.other);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

但往往会把对象中的函数赋值给一个变量,这样其实又变成普通函数了,所以使用普通函数的规则。

var studentDoSth = student.doSth;
studentDoSth(); // 'window'
// 用call类比则为:
studentDoSth.call(undefined);
1
2
3
4

# call、apply、bind 调用模式

需要注意的是,指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。

  • 相同点:改变 this 指向为函数中的第一个参数
  • 不同点:call 其余参数是一个一个的形式;apply 其余参数是一个数组;bind 返回一个改变了 this 指向的函数,这个返回的函数的 this 的指向不会变,原函数可以变

# 箭头函数调用模式

箭头函数和普通函数的重要区别:

  • 1、没有自己的this、super、arguments和new.target绑定。
  • 2、不能使用new来调用。 3、没有原型对象。 4、不可以改变this的绑定。 5、形参名称不能重复。

箭头函数中没有this绑定,必须通过查找作用域链来决定其值。 如果箭头函数被非箭头函数包含,则this绑定的是最近一层非箭头函数的this,否则this的值则被设置为全局对象。

var name = 'window';
var student = {
    name: 'wudeh',
    doSth: function(){
        // var self = this;
        var arrowDoSth = () => {
            // console.log(self.name);
            console.log(this.name);
        }
        arrowDoSth();
    },
    arrowDoSth2: () => {
        console.log(this.name);
    }
}
student.doSth(); // 'wudeh'
student.arrowDoSth2(); // 'window'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

其实就是相当于箭头函数外的this是缓存的该箭头函数上层的普通函数的this。如果没有普通函数,则是全局对象(浏览器中则是window)。 也就是说无法通过call、apply、bind绑定箭头函数的this(它自身没有this)。而call、apply、bind可以绑定缓存箭头函数上层的普通函数的this。 比如:

var student = {
    name: 'wudeh',
    doSth: function(){
        console.log(this.name);
        return () => {
            console.log('arrowFn:', this.name);
        }
    }
}
var person = {
    name: 'person',
}
student.doSth().call(person); // 'wudeh'  'arrowFn:' 'wudeh'
student.doSth.call(person)(); // 'person' 'arrowFn:' 'person'
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 构造函数调用模式

function Student(name){
    this.name = name;
    console.log(this); // {name: 'wudeh'}
    // 相当于返回了
    // return this;
}
var result = new Student('wudeh');
1
2
3
4
5
6
7

使用new操作符调用函数,会自动执行以下步骤。

  • 创建了一个全新的对象。
  • 这个对象会被执行[[Prototype]](也就是__proto__)链接。
  • 生成的新对象会绑定到函数调用的this。
  • 通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上。
  • 如果函数没有返回对象类型Object(包含Functoin, Array, Date, RegExg, Error),那么new表达式中的函数调用会自动返回这个新的对象。

可以知道:new操作符调用时,this指向生成的新对象。 特别提醒一下,new调用时的返回值,如果没有显式返回对象或者函数,才是返回生成的新对象。

function Student(name){
    this.name = name;
    // return function f(){};
    // return {};
}
var result = new Student('wudeh');
console.log(result); {name: 'wudeh'}
// 如果返回函数f,则result是函数f,如果是对象{},则result是对象{}
1
2
3
4
5
6
7
8

# 原型链中的调用模式

function Student(name){
    this.name = name;
}
var s1 = new Student('若川');
Student.prototype.doSth = function(){
    console.log(this.name);
}
s1.doSth(); // '若川'
1
2
3
4
5
6
7
8

对象上的方法调用模式,自然是指向生成的新对象。 如果该对象继承自其它对象,同样会通过原型链查找。

# DOM事件处理函数调用

addEventerListener、attachEvent、onclick

<button class="button">onclick</button>
<ul class="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<script>
    var button = document.querySelector('button');
    button.onclick = function(ev){
        console.log(this);
        console.log(this === ev.currentTarget); // true
    }
    var list = document.querySelector('.list');
    list.addEventListener('click', function(ev){
        console.log(this === list); // true
        console.log(this === ev.currentTarget); // true
        console.log(this);
        console.log(ev.target);
    }, false);
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

onclickaddEventerListener是指向绑定事件的元素。 一些浏览器,比如IE6~IE8下使用attachEvent,this指向是window。 顺便提下:面试经常考察ev.currentTarget和ev.target的区别。 ev.currentTarget是绑定事件的元素,而ev.target是当前触发事件的元素。

内联事件处理函数调用

<button class="btn1" onclick="console.log(this === document.querySelector('.btn1'))">点我呀</button>
<button onclick="console.log((function(){return this})());">再点我呀</button>
1
2

第一个是button本身,所以是true,第二个是window。这里跟严格模式没有关系。

# 优先级

箭头函数的this是上层普通函数的this或者是全局对象(浏览器中是window),所以排除,不算优先级。

var name = 'window';
var person = {
    name: 'person',
}
var doSth = function(){
    console.log(this.name);
    return function(){
        console.log('return:', this.name);
    }
}
var Student = {
    name: '若川',
    doSth: doSth,
}
// 普通函数调用
doSth(); // window
// 对象上的函数调用
Student.doSth(); // '若川'
// call、apply 调用
Student.doSth.call(person); // 'person'
new Student.doSth.call(person);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

如果是Student.doSth.call(person)先执行的情况下,那new执行一个函数。是没有问题的。 然而事实上,这代码是报错的。运算符优先级是new比点号低,所以是执行new (Student.doSth.call)(person) 而Function.prototype.call,虽然是一个函数(apply、bind也是函数),跟箭头函数一样,不能用new调用。所以报错了。

Uncaught TypeError: Student.doSth.call is not a constructor

这是因为函数内部有两个不同的方法:[[Call]]和[[Constructor]]。 当使用普通函数调用时,[[Call]]会被执行。当使用构造函数调用时,[[Constructor]]会被执行。call、apply、bind和箭头函数内部没有[[Constructor]]方法。

它们的优先级是new 调用 > call、apply、bind 调用 > 对象上的函数调用 > 普通函数调用。

最近更新时间: 2021/08/25 17:25:09
最近更新
01
2023/07/03 00:00:00
02
2023/04/22 00:00:00
03
2023/02/16 00:00:00