this 是什么?

JavaScript this 关键词指的是它所属的对象。

它拥有不同的值,具体取决于它的使用位置:
在方法中,this 指的是所有者对象。
单独的情况下,this 指的是全局对象。
在函数中,this 指的是全局对象。
在函数中,严格模式下,this 是 undefined。
在事件中,this 指的是接收事件的元素。

// 创建对象:
var person = {
  firstName: "Bill",
  lastName : "Gates",
  id     : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
在本例中,this 代表 person 对象。
因为 person 对象“拥有” fullName 方法。
Bill Gates
var x = this;
在本例中,this 引用 window 对象:
[object Window]
"use strict";
var x = this;
在本例中,this 引用 window 对象:
[object Window]
function myFunction() {
  return this;
}
在本例中,this 代表“拥有” myFunction 的对象:
[object Window]
"use strict";
function myFunction() {
  return this;
在函数中,默认地,this 引用全局对象。
在严格模式中,thisundefined,因为严格模式不允许默认绑定:
undefined
}
<button onclick="this.style.display='none'">单击来删除我!</button>HTML 事件处理程序中,this 指的是接收此事件的 HTML 元素:

var person = {
  firstName  : "Bill",
  lastName   : "Gates",
  id         : 678,
  myFunction : function() {
    return this;
  }
};
在此例中,this 是 person 对象(person 对象是该函数的“拥有者”):
var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"Bill",
  lastName: "Gates",
}
person1.fullName.call(person2);  // 会返回 "Bill Gates"
显式函数绑定
call()apply() 方法是预定义的 JavaScript 方法。
它们都可以用于将另一个对象作为参数调用对象方法。
您可以在本教程后面阅读有关 call()apply() 的更多内容。
在下面的例子中,当使用 person2 作为参数调用 person1.fullName 时,this 将引用 person2,即使它是 person1 的方法:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值