有人能解释一下这两个代码之间的区别吗?为什么第二个有效,而第一个无效;t

Can anyone explain the difference between those two codes? And why does the second one work and the first doesn't?

本文关键字:第二个 有效 为什么 无效 第一个 区别 之间 一下 能解释 代码 两个      更新时间:2023-09-26

HTML:

<input type="button" name="red" onclick="dis()">

这是JavaScript的第一个代码:

function dis() {
  alert(this.name)
}

这是工作版本:

HTML:

  <input type="button" name="red" onclick="dis(this)">

JavaScript:

function dis(a) {
  alert(a.name)
}

在第一种情况下,您在全局范围内调用dis()。在这种情况下,this是全局对象

在第二种情况下,您还可以在全局范围内调用dis()。但您将当前的this值作为参数传递给函数。

为了使第一种情况和第二种情况相同,你应该这样重写:

<input type="button" name="red" onclick="dis.call(this)">

通过这种方式,您可以将当前this传递给函数。

这方面的一般规则是查看函数左侧的内容(换句话说,谁被称为函数):

dis()     // -> on the left nothing stands, so `this` will correspond to global object
a.dis()   // -> on the left `a` stands, so `this` will correspond to `a`
new dis() // -> on the left `new` keyword stands, so `this` will correspond to newly created object