Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2411

javascript accessing object

consider the following code:

 <script>
  person={
          firstname:"John",
          lastname:function(){alert(this.firstname)}
         }
          person.lastname();
 </script>

like local variables can be accessed from anywhere within the function ,to access the property of an object why should we use this keyword?Since we are within the object is the use of this keyword compulsory?

Upvotes: 0

Views: 64

Answers (2)

Kamyar Nazeri
Kamyar Nazeri

Reputation: 26534

this keyword in JavaScript is a somehow different compared to other languages. The object bound to this in the current scope is determined by how the current function was called, it can't be set by assignment during execution, and it can be different each time the function is called!

var person1 = {
    firstname: "John",
    lastname: function () { alert(this.firstname) }
}

var person2 = {
    firstname: "James",
}
person2.lastname = person1.lastname.bind(person2);

var firstname = "Rick";

Simple call:

person1.lastname();  // "John"

Context change call:

person1.lastname.call(window);  // "Rick"

Bound Function call:

person2.lastname();  // "James"

this also behaves differently on the prototype chain or in DOM event handlers

Upvotes: 2

kamituel
kamituel

Reputation: 35970

That's because in JavaScript, when you use firstname, interpreter is looking for that variable in the current scope and, later, in all parent scopes. But objects are not forming scopes.

Because of that, you need to access firstname via a special variable - this.

Hint: functions are creating scopes, so on example:

 var person = function () {
     var firstname = "John";

     return {
         lastname: function () {
             alert(firstname)
         }
     };
 }();

would work without this.

Upvotes: 2

Related Questions