在讲this指向问题中,最重要的一句话就是“谁调用,就指向谁”。
// 1、默认绑定规则
//全局作用域下this指的就是window
console.log(this === window);//true
//两个对象因为地址不同,所以肯定不相同
console.log({} === {});//false
//函数中的this也指向window
function test() {
console.log(this === window);//true
}
// 函数的独立调用
test();
//2、隐式绑定调用(谁调用就指向谁)
var a = 1;
var obj = {
a: 2,
foo: function () {
console.log('谁调用,指向谁', this === obj);//true
function tests() {
console.log('tests', this === window);//true
}
tests();
//function函数-立即执行函数
(function () {
console.log('立即执行函数', this === window);//true
})();
function fn() {
console.log('fn-闭包', this === window)//true
}
return fn
}
}
//对象中函数的调用
//闭包
obj.foo()();
//变量赋值
var b = 0;
function fun() {
console.log(this)
}
var obj1 = {
b: 1,
fun: fun
}
obj1.fun();//this => obj
var bar = obj1.fun;
bar()//this => window
// 参数赋值的情况
var a = 0;
function foo() {
console.log(this === window)//true
}
function bar(fn) {
console.log(this === window);//true
fn();
}
var obj = {
a: 1,
foo: foo
}
bar(obj.foo);
//父函数有能力决定子函数的this指向
var arr = [1, 2];
arr.forEach(function (item, index, arr) {
console.log(this)//this => window
})
arr.forEach(function (item, index, arr) {
console.log(this)//this => obj
}, obj)
//3、显示绑定:call、apply、bind
var a = 0;
obj = {
a: 1,
fun1: function () {
console.log(this)
}
}
obj.fun1(); //this => obj
var fun2 = obj.fun1;
fun2();// this => window
fun2.call(obj); //this => obj
fun2.apply(obj); //this => obj
fun2.bind(obj)(); //this => obj
//4、new 绑定
function Person() {
this.a = 1;
return this;
}
var person = new Person();//this =>实例化对象
console.log(person)//输出Person {a: 1}
这是一道课后习题,大家把自己的答案留言到评论区,让我来看看你们的水平吧,之后答案也会公布在评论区。
var name = '222'
var a = {
name: '111',
say: function(){
console.log(this.name);
}
}
var fun = a.say;
fun();
a.say();
以上就是this指向问题,接下来会讲箭头函数指向问题。
我是前端Dai,一个会将自己平时项目中常见的问题以及笔试面试的知识在CSDN与大家分享的coder,希望大家一起进步,加油。