彻底掌握this,call,apply

说起js里面比较头疼的知识点,this的指向,call与apply的理解这三者肯定算的上前几,好的js开发者这是必须迈过的槛.今天就总结下这三者紧密相连的关系.

首先推荐理解call的用法

  • Function.prototype.call

    格式:fx.call( thisArg [,arg1,arg2,… ] );

  1. call的传参个数不限,第一个数表示调用函数(fx)函数体内this的指向.从第二个参数开始依次按序传入函数.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var age = 40;
var xiaoMing = {
age:30
};
var xiaoLi = {
age: 20
};
var getAge = function(){
console.log(this.age);
};
getAge.call( xiaoMing ); //30 表示函数this指向xiaoMing
getAge.call(xiaoLi); //20 表示函数this指向xiaoLi
getAge.call(undefined);//40 getAge.call(undefined)==getAge.call(null)
getAge.call(null);//40
getAge(); //40

如果我们传入fx.call()的第一个参数数为null,那么表示函数fx体内this指向宿主对象,在浏览器是Window对象,这也解释了getAge.call(undefined);//40。

在此基础我们可以理解为 getAge()相当于getAge.call(null/undefined),扩展到所有函数,
fx()==fx.call(null) == fx.call(undefined)

值得注意的是严格模式下有点区别: this指向null

1
2
3
4
5
6
7
 
var getAge = function(){
'use strict'
console.log(this.age);
};
 
getAge(null);//报错 age未定义

再来理解this的使用

this的常用场景:

  • this位于一个对象的方法内,此时this指向该对象
1
2
3
4
5
6
7
8
9
10
11
12
 
var name = 'window';
 
var Student = {
name : 'kobe',
getName: function () {
console.log(this == Student); //true
console.log(this.name); //kobe
}
}
 
Student.getName();
  • this位于一个普通的函数内,表示this指向全局对象,(浏览器是window)
1
2
3
4
5
6
7
8
var name = 'window';
 
var getName = function () {
var name = 'kobe'; //迷惑性而已
return this.name;
}
 
console.log( getName() ); //window
  • this使用在构造函数(构造器)里面,表示this指向的是那个返回的对象.
1
2
3
4
5
6
7
8
var name = 'window';
//构造器
var Student = function () {
this.name = 'student';
}
 
var s1 = new Student();
console.log(s1.name); //student

注意: 如果构造器返回的也是一个Object的对象(其他类型this指向不变遵循之前那个规律),这时候this指的是返回的这个Objec.

1
2
3
4
5
6
7
8
9
10
11
var name = 'window';
//构造器
var Student = function () {
this.name = 'student';
return {
name: 'boyStudent'
}
}
 
var s1 = new Student();
console.log(s1.name); //boyStudent
  • this指向失效问题
1
2
3
4
5
6
7
8
9
10
11
12
13
 
var name = 'window';
 
var Student = {
name : 'kobe',
getName: function () {
console.log(this.name);
}
}
 
Student.getName(); // kobe
var s1 = Student.getName;
s1(); //window

原因: 此时s1是一个函数

1
2
3
function () {
console.log(this.name);
}

对一个基本的函数,前面提过this在基本函数中指的是window.

  • 在开发中我们经常使用的this缓存法 ,缓存当前作用域下this到另外一个环境域下使用

最后理解apply的用法 Function.prototype.apply

格式: fx.apply(thisArg [,argArray] ); // 参数数组,argArray

  1. apply与call的作用是一样的,只是传参方式不同,
  2. apply接受两个参数,第一个也是fx函数体内this的指向,用法与call第一个参数一致.第二个参数是数组或者类数组,apply就是把这个数组元素传入函数fx.
1
2
3
4
5
6
7
 
 
var add = function (a ,b ,c) {
console.log(a +b +c);
}
 
add.apply(null , [1,2,3]); // 6

再吃透这个题目就ok

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
var a=10;
var foo={
a:20,
bar:function(){
var a=30;
return this.a;
}
}
foo.bar()
//20
(foo.bar)()
//20
(foo.bar=foo.bar)()
//10
(foo.bar,foo.bar)()
//10

哪里说错或者有更好的理解希望大家指出来.共同进步.

原文地址:https://www.cnblogs.com/libin-1/p/6099896.html