ionox0
ionox0

Reputation: 1111

Javascript scope/this

How come when I do:

function Dog(){
   this.firstName = 'scrappy';
}

Dog.firstName is undefined?

However then I can do:

Dog.firstName = 'scrappy';

And now Dog.firstName returns 'scrappy'?

Upvotes: 0

Views: 327

Answers (2)

Jimmy Breck-McKye
Jimmy Breck-McKye

Reputation: 3034

The Dog() function is just the constructor, so you're calling firstname on the constructor rather than an instance of it. This isn't defined just by virtue of it being defined on the returned objects, they're totally separate things. However, because you can augment functions with fields, you were able to assign a value to dog.firstName anyway.

First, let me demonstrate the difference between a constructor and an instance:

function Dog() {
    this.firstName = 'scrappy';
}

Dog.firstname; // undefined on the constructor

Dog.prototype; // defined on constructor, returns an empty object

var myDog = new Dog();

myDog.firstname; // defined on instance, returns 'scrappy'

myDog.prototype; // undefined on instance

As you can see, a constructor (a function that returns an object) is a totally different thing to the object it returns, and has totally different fields as a result. What you were seeing when you got Dog.firstname to return 'scrappy' was the result of adding a new field to the constructor. This is doable, but remember, adding a field to the constructor will not add the same field to the constructed. Consider:

Dog.someNewProperty = 'whatever';

var myDog = new Dog();

Dog.someNewProperty; // 'whatever'
myDog.someNewProperty; // undefined

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816242

How come when I do ... Dog.firstName is undefined?

Because...

However then I can do ... And now Dog.firstName returns 'scrappy'?

Functions are just objects, so you can assign any property to it.

Upvotes: 11

Related Questions