Javascript Prototypes (the one like Closures not JQuery)
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 librar开发者_高级运维y?
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?
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.
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.
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( );
There's a few issues with the example:
Person
should be declared withvar
. It's advisable to always do this with variables.- The typo, noted in other answers.
- The getter/setter pattern, likely influenced by C#'s properties. Unless you're doing something complicated, this is probably overkill in JavaScript and your code would be clearer simply using a property. As an aside, the new ECMAScript 5 spec introduced getter and setter methods for properties to the language, and some browsers have implemented them, but they're not yet widespread enough to use on the web.
精彩评论