Reputation: 13175
I just picked up a new book on ASP.NET and AJAX and in it there is a sample like this:
Person = function(firstName) {
this._firstName = firstName;
}
Person.prototype = {
get_FirstName = function() {return this._firstName;}
}
I noticed immediately this is not what I am used to, and FireBug apparently agrees with me that its wonky. I am used to something like:
Person.protoype = {
get_FirstName: function() {return this._firstName;}
}
Is this just a typo on the author's part or is he maybe using a feature from the ASP.NET AJAX library?
Also, is there a difference between the preceding function and this:
Person.protoype.get_FirstName = function() {
return this._firstName;
}
Did the author just smush together two acceptable declarations of the same function?
Upvotes: 2
Views: 187
Reputation: 324607
There's a few issues with the example:
Person
should be declared with var
. It's advisable to always do this with variables.Upvotes: 1
Reputation: 71880
For the second part of your question, if you use don't assign a new object to the prototype property you can use inheritance:
Person = function( ) {
};
Person.prototype = new Individual( );
Person.protoype.set_LastName = function( lastname) {
this.lastName = lastname
};
//inherited from Individual:
Person.get_FirstName( );
Upvotes: 1
Reputation: 1863
for your first question yes that is a typo or mistake - it's not valid javascript.
about your last question actually there is a difference between the two examples if there was already something attached to the prototype. The first one, which sets the prototype attribute, will remove anything else that had previously been done to the prototype, while the second merely adds to what's already there. I would (and do) use the second way, adding a new attribute to the prototype.
Upvotes: 1
Reputation: 113926
First question, yes I believe that was a typo.
Second question, yes there is a difference. The ill advised:
Constructor.prototype = { method : function(){} }
inherits from an anonymous object (the {}
) in which the method was defined.
If this is done a second time then the previous method would disappear because the inheritance chain would now point to a new anonymous object.
The more usual:
Constructor.prototype.method = function(){}
simply defines a new method.
Upvotes: 2