javascript中this关键字

// 例子1 默认绑定
console.log("----例子1----");
function a() {
  function b() {
    console.log(this);
    function c() {
      // 严格模式下 调用函数的时候不会默认绑定全局
      "use strict";
      console.log(this);
    }
    c();
  }
  // 此处等同于window.b() 因为默认绑定全局,没有显示的指明谁在调用b()
  // 在node环境中为node global对象 ,window环境下为window对象
  b();
}
// 跟b()同理
a();

// 例子2 隐式绑定
// es5 function this指向,默认指向调用者,即谁调用我 我指向谁
console.log("----例子2----");

// 注意此处的全局声明使用var而不是let/const.
// es6规定let/const声明的变量不会默认挂载到window下
// 可以尝试修改为let 会发现全局的name为undefined
// let name = '全局小白'
var name = "全局小白";

function special() {
  console.log(this.name);
}

function immediate(callback) {
  callback();
}

let girl = {
  name: "小红",
  detail: function () {
    console.log(this.name);
    // console.log(this)
  },
  woman: {
    name: "小白",
    detail: function () {
      console.log(this.name);
    },
  },
  special: special,
  bibao: function () {
    // 此处为闭包
    return function () {
      console.log(this.name);
    };
  },
  test: function (param1, param2) {
    console.log(param1, param2);
    console.log(this.name);
  },
};

let girl2 = {
  name: "我是girl2",
};

let boy = girl.detail;

girl.detail(); // 小红
girl.woman.detail(); // 小白
girl.special(); // 小红  注意此处只是special属性引用了全局声明的special函数,最后还是谁调用指向谁
boy(); // 全局小白
girl.bibao()(); // 全局小白
immediate(girl.detail); // 全局小白

// call,bind,apply 显示绑定this
girl.test.call(girl2, 1, 2);
// bind会返回一个修改this后的函数,所以需要重新执行
girl.test.bind(girl2)(1, 2);
girl.test.apply(girl2, [1, 2]);

// 例子3
// 箭头函数this
// 默认指向全局(简单对象本身没有上下文)
// 如果被普通函数包裹则指向函数所在【父级上下文】

let mother = {
  name: "小红",
  detail: () => {
    console.log(this.name);
  },
  test: function () {
    let name = "我是内部小红";
    return () => {
      console.log(name); // 注意此处为原型链 箭头函数没有会继续往上寻找,找到外侧的name
      console.log(this.name); // 此处因为被function包裹,而function本身是mother里的test属性,所以指向mother
    };
  },
};
mother.detail();
mother.test()();

// 箭头函数跟普通函数区别 ()=>{}
// 没有new 没有原型链 不能作为构造函数 默认是匿名函数
// 不可修改this,this在声明时已经确定
// call apply bind 可以用 , 但不会影响this指向
// 声明只能用函数表达式 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值