0%

js里的this

这周逛 v2 由看到有人发 js 的 this 的题目,然后说能做出来的都得算多少年薪……..个人感觉这种知识大部分都是为了应付面试,而且道格拉斯克罗克福特 说过 js 是最好的语言,但是你要用它 good part.
不过周末正好看到 相关的一篇文章,发出来,比如有时候为什么调用要加 that =this 避免找不到 还是有点作用的毕竟.

If the function is defined as an arrow function

1
2
3
const arrwoFunction = ()=>{
console.log(this)
}

this 和父级 this 是一样.

  • call or apply 不能改变 箭头函数 的 this

Otherwise, if the function/class is called with new

this 被设置成 Object.create(….prototype)的返回值

1
2
3
4
5
6
7
class MyClass{
constructor(){
console.log(
this.constructor === Object.create(MyClass.prototype).constructor
}
// Logs true
new MyClass()

Otherwise, if the function has a ‘bound’ this value

1
2
3
4
5
6
function someFunction() {
return this;
}

const boundObject = { hellp: "world" };
const boundFunction = someFunction.bind(boundObject);

当 boundFuncton 被调用,this 指向 boundObject

1
2
3
4
// false
someFunction() === boundObject;
//true
boundFunction() === boundObject;

Otherwise, if this is set at call-time

1
2
3
4
5
6
7
8
9
10
function someFunction() {
return this;
}

const someObject = { hellp: "world" };

// true
console.log(someFunction.call(someObject) === someObject);
// true
console.log(someFunction.apply(someObject) === someObject);

Otherwise, if the function is called via a parent object

1
2
3
4
5
6
7
8
9
const obj = {
someMethod() {
return this;
},
};

// true

obj.someMethod() === obj;

in this case the function is called as a member of obj, so this will be obj,the link is broken if the function is called without its object

1
2
3
const { someMethod } = obj;
//false
someMethod() === obj;

Otherwise, if the function or parent scope is in strict mode

1
2
3
4
5
6
7
function someFunction() {
"use strict";
return this;
}

// true
someFunction() === undefined;

如果父级是严格模式,不写’use strict’ 结果也是一样的

Otherwise

1
2
3
4
5
6
function someFunction() {
return this;
}
// true

someFunction() === globalThis;

this 指向全局 this