0

JavaScript and I believe all other OO languages have a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object's value property, given the object and the high and low values

function validate(obj, lowval, hival) {
  if ((obj.value < lowval) || (obj.value > hival))
    alert("Invalid Value!");
}

Then, you could call validate in each form element's onchange event handler, using this to pass it the element, as in the following example:

<input type="text" name="age" size="3"
  onChange="validate(this, 18, 99)">

In general, this refers to the calling object in a method.
I understand all of this usage, I just have a little question: how this works under the hood? I mean how does the method know which object is calling if you dont specify the name?

lychee
  • 1,771
  • 3
  • 21
  • 31
  • Methods don't "know" anything. The Javascript engine invokes them and specifies what `this` is at any given time based on the rules for how `this` works. – JLRishe Mar 16 '15 at 16:33
  • your examples contain bad practices (using alert, using js event listeners in html code) – micnic Mar 16 '15 at 16:34
  • Well, except that javascript doesn't have a concept of "methods". And that's why `this` works a bit different. – Bergi Mar 16 '15 at 16:35
  • @micnic it is from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – lychee Mar 16 '15 at 16:36

1 Answers1

2

In compilers I have worked with, this is done by passing an implicit parameter on the call stack along with the explicit parameters. Of course it may vary based on the compilation or interpretation engine, but this is the simplest approach.

radiaph
  • 4,001
  • 1
  • 16
  • 19
  • Which JS compilers did you work with? – Bergi Mar 16 '15 at 16:37
  • None, I meant compilers for other languages. – radiaph Mar 16 '15 at 16:38
  • @Bergi, colony interpreter written in lua by Tessel team, it is an incomplete JS implementation, checkout this file https://github.com/tessel/runtime/blob/master/src/colony/lua/colony-js.lua "this" is the first argument in functions – micnic Mar 16 '15 at 16:42