0

What's difference of this in the following two cases?

Case 1

var Person = function() { this.name="Allen Kim" }
Person.name; //undefined

Case 2

var Person = function() { this.name="Allen Kim" }
var me = new Person();
me.name // Allen Kim

Just wanted to understand how this scope works on both cases.

3 Answers 3

6

Every function in JavaScript is itself an object. So Person.name retrieves the name property from the function itself, which was never set; hence undefined.

You can try this my setting it directly:

Person.name = "John";
Person.name; // "John"

When assigning a property from within the constructor via

this.name = "Allen Kim";

you're setting the property on that instance. When you then instantiate an object with:

var me = new Person();

your constructor will add the name property to me, since this referes to the object being created.


Here are the basic steps taken by the JavaScript engine when calling a constructor function with the new keyword:

  1. Calls the constructor with this set to a new clean object.
  2. Sets the internal [[Prototype]] property of your new object to the constructor's prototype (which, in some implementations, is then available through __proto__).
  3. Sets up the constructor property of your new object as a reference to the constructor function (so instead of the non-standard me.__proto__, you could access the prototype via me.constructor.prototype).
  4. Returns said object.

Note that this is a very basic explanation. There are many other things not included here, but this should give you the gist of it.

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

2 Comments

thanks, can you describe what does 'new' do in javascript. I read yehudakatz.com/2011/08/12/… and not very clear about it yet. I may have to read it again an again.
@bighostkim - That article you linked to is a very good article, but does not directly answer your question. I added a brief rundown to my answer.
1

On the first case you are looking for a static property on the function itself.

The second case you are returning an instance of an object that has the property by calling a constructor function. Its not really a matter of scope.

Comments

1
var Person = function() { this.name="Allen Kim" }
Person.name; //undefined due to the fact that there is no Person object.

var Person = function() { this.name="Allen Kim" }
var me = new Person();
me.name // Allen Kim --> Person `me`'s name

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.