简体   繁体   English

什么时候需要在javascript函数中将对象作为参数传递?

[英]When is it necessary to pass object as argument in a function in javascript?

if I don't want to use 'this' as an object and directly write the function without passing 'this' as an object and directly write this.src="" in the function why would that not work?? 如果我不想使用“ this”作为对象并直接编写函数而没有通过“ this”作为对象并直接在函数中编写this.src =“”,那为什么不起作用?

<body>
<script type="text/javascript">
  function picture(yolo){
    yolo.src="3Nail.jpg";
  }

  function normal(yolo) {
    yolo.src="4Nail.jpg";
  }
</script>

 <img onmouseover="picture(this)" onmouseout="normal(this)" src="1nail.jpg" alt="n1"/>
<img onmouseover="picture(this)" onmouseout="normal(this)" src="2nail.jpg" alt="n2"/>

As the functions are not associated with event handlers, their this references the global window object. 由于功能不与事件处理程序相关联的,他们的this引用全局窗口对象。 In order to avoid having to use the variable yolo as an argument, you can supply the this binding to the functions by calling them with this as the context using call as shown below. 为了避免必须使用变量yolo作为参数,可以通过使用call将此作为上下文来调用它们,从而为函数提供this绑定,如下所示。

js JS

  function picture(){
    this.src="3Nail.jpg";
  }

  function normal() {
    this.src="4Nail.jpg";
  }

html HTML

<img onmouseover="picture.call(this)" onmouseout="normal.call(this)" src="1nail.jpg" alt="n1"/>
<img onmouseover="picture.call(this)" onmouseout="normal.call(this)" src="2nail.jpg" alt="n2"/>

Inside the img tag, this refers to that specific img element. img标签内, this是指特定的img元素。 Here, inside the function, this would be window . 在函数内部, thiswindow In general, the this inside a function refers to the object the function belongs to. 通常,函数内部的this是指函数所属的对象。

Thus, if you were to call the function without passing that element from the img tag, the function would have no way of knowing which element it should update. 因此,如果要在不传递img标记中传递该元素的情况下调用该函数,则该函数将无法知道应更新哪个元素。 Of course, you can use query selectors inside the function to grab what you need -- but that only works if you always want to update the same element(s). 当然,您可以在函数内部使用查询选择器来获取所需的内容-但这仅在您始终想更新相同元素的情况下才有效。

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

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