文章目录
今天面试遇到了this 的问题,虽然理解。但是到问题上还是有点蒙圈。今天再搞一下。
this 永远指向函数运行时所在的对象,而不是函数被创建时所在的对象。
1.单独的this,指向的是window这个对象
alert(this); // this -> window
2.全局函数中的this,指向的是window这个对象
function demo() {
alert(this); // this -> window
}
demo();
在严格模式下,this是undefined.
function demo() {
'use strict';
alert(this); // undefined
}
demo();
3.函数调用的时候,前面加上new关键字 所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象。
function demo() {
//alert(this); // this -> object
this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr); // 'this is a test'
4.用call与apply,bind的方式调用函数
call()与apply()都是在特定的作用域中调用函数,等于设置函数体内this对象的值,以扩充函数赖以运行的作用域。
一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。
function demo() {
alert(this);
}
demo.call('abc'); // abc
demo.call(null); // this -> window
demo.call(undefined); // this -> window
5.定时器中的this,指向的是window
setTimeout(function() {
alert(this); // this -> window ,严格模式 也是指向window
},500)
6.元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.onclick = function(){
alert(this); // this -> 当前触发
}
}
7.对象中的方法,该方法被哪个对象调用了,那么方法中的this就指向该对象
let name = 'finget'
let obj = {
name: 'FinGet',
getName: function() {
alert(this.name);
}
}
obj.getName(); // FinGet
---------------------------分割线----------------------------
let fn = obj.getName;
fn(); //finget this -> window
字节题目:
inner = 'window';
function say() {
console.log(inner);
console.log(this.inner);
}
var obj1 = (function() {
var inner = '1-1';
return {
inner: '1-2',
say: function() {
console.log(inner);
console.log(this.inner);
}
}
})();
var obj2 = (function() {
var inner = '2-1';
return {
inner: '2-2',
say: function() {
console.log(inner);
console.log(this.inner);
}
}
})();
say();
//在window直接执行,指向的是Windows
obj1.say();
obj2.say();
obj1.say = say;
obj1.say();
obj1.say = obj2.say;
obj1.say();