彻底掌握this,call,apply

作者:日期:2017-03-10 23:09:17 点击:254

 Function.prototype.call

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

call的传参个数不限,第一个数表示调用函数(fx)函数体内this的指向.从第二个参数开始依次按序传入函数.

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

var getAge = function(){
'use strict'
console.log(this.age);
};
getAge(null);//报错 age未定义

再来理解this的使用

this的常用场景:

this位于一个对象的方法内,此时this指向该对象

var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
console.log(this == Student); //true
console.log(this.name); //kobe
}
}
Student.getName();

this位于一个普通的函数内,表示this指向全局对象,(浏览器是window)

var name = 'window';
var getName = function () {
var name = 'kobe'; //迷惑性而已
return this.name;
}
console.log( getName() ); //window

this使用在构造函数(构造器)里面,表示this指向的是那个返回的对象.

var name = 'window';
//构造器
var Student = function () {
this.name = 'student';
}
var s1 = new Student();
console.log(s1.name); //student

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

var name = 'window';
//构造器
var Student = function () {
this.name = 'student';
return {
name: 'boyStudent'
}
}
var s1 = new Student();
console.log(s1.name); //boyStudent

this指向失效问题

var name = 'window';
var Student = {
name : 'kobe',
getName: function () {
console.log(this.name);
}
}
Student.getName(); // kobe
var s1 = Student.getName;
s1(); //window

原因: 此时s1是一个函数

function () {       
console.log(this.name);
}

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

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

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

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

apply与call的作用是一样的,只是传参方式不同, 
apply接受两个参数,第一个也是fx函数体内this的指向,用法与call第一个参数一致.第二个参数是数组或者类数组,apply就是把这个数组元素传入函数fx.

var add = function (a ,b ,c) {
console.log(a +b +c);
}

add.apply(null , [1,2,3]);
// 6

再吃透这个题目就ok

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

上一篇: ES6新特性学习

下一篇: ES6(ECMAScript 6)箭头函数详解