0

confuse on this of javascript

<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

myFather=new person("John","Doe",50,"blue");

document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>

John refer to this.firstname or firstname after it? this.firstname refer to what?

  • [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)`.something` is a *property* of the instance, while the other is a plain variable (initialized as a parameter here). They both have the same value (the string `"John"`) after one is assigned to the other. – Bergi Oct 01 '13 at 13:43
  • For this specific question `this` refers to the new object created by the `new` keyword. See this answer to another question for a full description of how `this` works in javascript: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Oct 01 '13 at 13:45
  • When Googled I see http://www.sitepoint.com/what-is-this-in-javascript/ and http://www.quirksmode.org/js/this.html – Ashok Oct 01 '13 at 13:46
  • @Ashok: Don't refer to quirksmode for `this`! [It's](http://www.quirksmode.org/js/events_tradmod.html#link3) plain wrong, or completely restricted to event handling. Better link to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Bergi Oct 01 '13 at 13:47

2 Answers2

0

this.firstname refers to the property firstname of the object referring. In your case, myfather is the object, so this.firstname refers to firstname of myfather.

Rajesh
  • 3,743
  • 1
  • 24
  • 31
0

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript

here this.firstname refer the owner of the page.

hope it will helps you.

kiran
  • 190
  • 1
  • 1
  • 13
  • `person` is a constructor here (and called as such), so it's neither a method nor has an owner, nor does `this` refer to the page or `window` – Bergi Oct 01 '13 at 13:49
  • so who is right? @Bergi can explain more? I thought this should refer to person function? – Kaitlyn Sacco Oct 01 '13 at 13:51
  • @KaitlynSacco: [the `this` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) is a confusing beast, as it depends on *how* the function is *called*. In your case, it refers to the new instance object which is assigned to `myFather` after the initialisation. – Bergi Oct 01 '13 at 13:54