0

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?

1
  • Yes, unless you want to use person.firstname Commented Apr 4, 2013 at 6:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

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.