2

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??

<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"/>

5
  • 2
    Show us how you are calling these functions. Commented Apr 18, 2016 at 22:50
  • The this keyword just means something different when it's in a different scope. That's why it doesn't work. Commented Apr 18, 2016 at 22:51
  • Hey, am calling these functions using onmouseover event handler Commented Apr 18, 2016 at 22:54
  • So, is it that we cant use 'this' directly in a function?? Commented Apr 18, 2016 at 22:54
  • Well, you can use it, but it doesn't refer to the same thing as this in the event handler. Check out the MDN docs on the this keyword Commented Apr 18, 2016 at 22:55

2 Answers 2

2

As the functions are not associated with event handlers, their this references the global window object. 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.

js

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

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

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"/>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton! .call is really helpful
1

Inside the img tag, this refers to that specific img element. Here, inside the function, this would be window. In general, the this inside a function refers to the object the function belongs to.

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. 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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.