【前端基础知识】this指向问题,function函数下,各种类型的this指向问题你都会了吗?内附【课后习题】|答案评论区见|

在讲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,希望大家一起进步,加油。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Dai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值