Jump to content

Need help better understanding the 'this' keyword


Recommended Posts

Hello, I need some help understanding the 'this' keyword.

var person=function(name,age){this.name=name;this.age=age;};var Bob=new person("bob",23);

for that you can just do Bob.age and get his age but I can't figure out a way to do this:

var person=function(name,age){this.name=name;this.age=age;this.printAge=function(){console.log(this.age);};};var Bob=new person("Bob",23);Bob.printAge();

Thank You

Link to comment
Share on other sites

A few points:

  1. Your code works, what's the problem? :)
  2. It's a widely-accepted convention to give instantiatable functions (class-like functions like your 'person' function) names that start with a Capital Letter. Whereas instances normally have lower-case names. It's only a convention, but everyone does it so I'd suggest you do it too
  3. "this" is the current context. Complicated subject, I recommend reading this explanation
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...