函数的调用方式
- 作为函数直接调用:this的指向取决于函数调用方式,调用时的上下文
// 1. 函数定义,调用
function test(){return this}; //非严格模式下,返回window;严格模式下,返回undefined
const a = test(); // a = window;
// 2. 立即调用函数表达式
(function test(){return this})() //window
- 作为方法调用: this的指向取决于调用方法的对象
const obj = {};
const obj2 = {};
const func = function(){return this};
obj.test = func;
obj2.test = func;
const target = obj.test(); // target = obj
const target2 = obj2.test(); // target2 = obj2;
const target3 = func; // target3 =window;
- 构造函数方式
首先说明一下使用构造函数调用函数的过程:
- 创建一个新的空对象;
- 该对象作为this参数传递给构造函数,从而成为构造函数的函数上下文;
- 如果构造函数没有返回值,新构造的对象作为new运算符的返回值;如果构造函数返回一个对象,则该对象作为整个表达式的值返回,而传入构造函数的this将被丢弃,在构造函数中对this的操作都是无效的;如果构造函数返回的是非对象类型,则忽略返回值,返回新创建的对象。
// 1. 没有返回值
function Test(){
this.func = function(){return this}
}
const a = new Test(); // a.func() = a;
const b = new Test(); // b.func() = b
// 2. 返回非对象
function Test(){
this.func = function(){return this}
return 1;
}
const res = Test(); // res = 1;
const a = new Test(); // a.func() = a;
const b = new Test(); // b.func() = b;
// 3. 返回对象
const obj = {};
function Test(){
this.func = function(){return this}
return obj;
}
const a = new Test(); // a = obj ;new Test()时新建的对象,this指向被丢弃
- apply 和 call :可以显式的指定函数的上下文,this指向
function test(){
var res = 0;
for(var i = 0; i<argumentes.length; i++){
res += argumengts[i]
}
this.res = res;
}
var obj = {};
var obj2 = {};
test.apply(obj,[1,2,3]); // obj.res = 6
test.call(obj2,1,2,3); // obj2 = 6;
箭头函数
箭头函数中的this与声明所在的上下文相同,在创建的时候确定了this的指向
// 1. 创建的时候确定this指向
var button = {
clicked : false,
click:()=>{
this.clicked = true;
console.log(this === window) //true
}
}
// 2.创建的时候确定this指向 && 构造函数的this
function Test(){
this.func = () => this;
}
var obj = new Test();
var obj2 = {
func : obj.func
}
// obj.func() = obj; 回忆构造函数的过程
// obj2.func() = obj; 回忆构造函数的过程 + 箭头函数的this在声明的时候确定
bind创建新函数
创建新函数,并绑定到bind方法传入的参数中,新函数被绑定到指定的对象上。
function Test(){
this.func = function(){
return this;
}.bind(this) //在new的时候已经确定这个this值为obj
}
var obj = new Test();
var obj2 = {
func : obj.func
}
//obj.func() = obj;
//obj2.func() = obj