function t () {
console.log(this);
}
t();
// 输出是 window
普通函数
一般而言,对于普通函数,谁调用这个函数,this就指向谁。
1.不同对象实例对函数原型链上方法的调用:
Array.prototype.fn = function () {
console.log(this);
}
let arr = [1,2,3];
arr.fn(); // (3) [1, 2, 3]
let arr2 = ['1','2','3'];
arr2.fn();//(3) ["1", "2", "3"]
arr 和 arr2 对于作为不同的 fn()调用者,fn中this的指向也不同。
2.函数嵌套调用:
function fn1() {
console.log('fn1的this:',this);
}
function fn2() {
console.log('fn2的this',this);
fn1();
}
fn2();
// 两个都是window
3.构造函数中的this:
function test() {
this.a = function() {
console.log(this);
}
}
let test1 = new test();
test1.a();
let test2 = new test();
test2.a();
// 两个输出都是 test {a: ƒ}
4.对象中的this:
let obj = {
fn : function () {
console.log(this);
}
}
obj.fn();
// 输出为:{fn: ƒ}
5. DOM事件绑定:
<body>
<button class='button'>点击我</button>
</body>
<script>
let button = document.querySelector('.button');
button.addEventListener('click',function() {
console.log(this);
});
</script>
// this 指向button按钮
// 谁触发指向谁
箭头函数
对于箭头函数,没有原型,不能成为构造函数,所以在其他情况做出对比.
this的值将解析为最接近的非箭头父函数或全局对象的值。
1. 函数的嵌套调用
function fn1() {
console.log('fn1:',this);
(() => {
console.log('array func:',this);
})();
}
fn1();
// fn1: Window
// array func: Window
不管是怎么嵌套
2.对象中的this:
let t = {
a:()=> {
console.log(this);
}
}
t.a();
// 输出:Window
window对象调用了t.a(),所以指向window;
3. 构造函数中的this:
function test() {
this.a = () => {
console.log(this);
}
}
let test1 = new test();
test1.a();
let test2 = new test();
test2.a();
// test {a: ƒ}
// test {a: ƒ}
4. 原型链中的方法:
Array.prototype.fn = () =>{
console.log(this);
}
let arr = [1,2,3];
arr.fn(); // window
let arr2 = ['1','2','3'];
arr2.fn();//window
5.DOM事件绑定
<body>
<button class='button'>点击我</button>
</body>
<script>
let button = document.querySelector('.button');
button.addEventListener('click',function() {
console.log(this);
});
</script>
//window
上述的例子,箭头函数的this似乎只能绑定到window上?
如何绑定箭头函数的this?
function test(fn) {
this.fn = fn;
}
let fn = {
tt: function a() {
(() => {
console.log(this);
})();
},
};
let t1 = new test(fn);
t1.fn.tt();
// 此时指向的是:{ tt: [Function: a] }
function test() {
this.fn = function a() {
(() => {
console.log(this);
})();
};
}
let t1 = new test();
t1.fn();
//此时指向 test { fn: [Function: a] }
参考文献: