Reputation: 1111
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
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
Reputation: 816242
How come when I do ...
Dog.firstName
is undefined?
Because...
... Dog
is never called, so the line this.firstName = 'scrappy';
is never executed and ...
... even if you call the function, this
probably won't refer to the function Dog
. You can call it in a way that this
refers to Dog
, but that is rather unusual . How the value of this
is determined has been explained extensively.
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