繁体   English   中英

谁能解释这两个代码之间的区别? 又为什么第二个有效而第一个无效呢?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM