js(node)中this的指向

452 阅读1分钟

案例一

function add(){
   this.name=13;
}
console.log(this);  // {}
console.log(global.name); // undefined

案例二

function add(){
   this.name=13;
}
add();
console.log(this); // {}
console.log(global.name);  // 13

(1) 全局中的this默认是一个空对象。并且在全局中this 与 global对象没有任何关系。函数中,通过this定义的变量就是相当于给global添加了一个属性,此时与全局中的this已经没有关系了。

(2) 故一般情况下node环境中,函数中,this指向的是global

(3)构造函数中,实例化时,this指向的是它的实例对象,而不是global

严格模式下


"use strict"
function add(){
console.log(this)
}
add();  // 严格模式下,函数中this的指向为undefined
add.call(this); //指向全局的this
add.call(global); //指向全局的 global

(1)通过call,bind,改变函数内部this的指向

(2)react中是严格模式的,所以使用箭头函数来,避免this指向问题