js中的this

本文深入解析JavaScript中this关键字的不同行为,包括默认指向全局对象、在严格模式下变为undefined、作为对象方法时指向该对象、使用new操作符时指向新创建的对象,以及箭头函数中this的特殊规则。
  • 默认的this是widnow或者global
this == window
function dd(){this == window;return this}
dd() == window
  • 方法内使用use strict,this是undefined的
function f2() {
  'use strict'; // see strict mode
  return this;
}
f2() === undefined;

function f2() {
  'use strict'; // see strict mode
  this.a='abc'
  return this;
}
f2() == undefined
  • 函数链式调用时(使用了 . 或者[]),this为调用前面对象的环境
var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};
console.log(o.f());
  • 函数使用了new操作符,生成新对象,this为新对象内的环境
function Foo () {
  this.x = 1;
}
var foo = new Foo();
foo.x
  • 箭头函数不包含this, 箭头函数的执行上下文的判定,就在其定义的时刻决定
function tt(){
    var aa= ()=>{console.log(this);}
    aa();
}
tt()


function Foo () {
  this.x = 1;
}

Foo.prototype.print = () => {
  console.log(this);
}
new Foo().print();
  • 匿名自执行函数,默认this为全局
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值