常见的this指向场景分为如下5种
1函数直接调用
function fn() {this.xx} fn() this => window
2对象属性方法
obj.fn() this => obj
3new构造函数
var son = new fn() this => son
4 call apply bind
fn.call(context) apply bind fn-this => context
5箭头函数
箭头函数是定义时候就已经确定词法环境 而不是谁调用 包裹它的作用域
var obj = {
fn: () => {
console.log(this)
}
}
obj.fn()
此时this指向外层块级作用域window
6构造函数return
function fn()
{
this.name = 'this指向';
return 1;
}
var a = new fn;
console.log(a.name);
function fn()
{
this.name = 'this指向';
return undefined;
}
var a = new fn;
console.log(a.name)
如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象那么this还是指向函数的实例。
实战案例1
function output(fn) {
fn()
}
var counter = {
count:0,
fn:function() {
this.count++
console.log(this, 'this')
}
}
output(counter.fn)
console.log(counter.count)
我们看函数的调用形式 fn()满足第一种情况所以 this指向window
实战案例2
var x = 1
function foo(x, y=function(){ x=2 }) {
x = 3
y()
console.log(x,'x-y')
}
foo()
console.log(x,'x')