Im trying to set up a variable and pass it constructor function essentailly like an anonymous type in c# but javascript doesnt seem to like it…
var aPerson = function Person(){
};
$(document).ready(function(){
Person.prototype.age = 22;
window.alert(aPerson .age);
});
Why cant I do this?
Personis only declared as part of youraPersonvariable, but it needs to be defined explicitly (e.g.function Person(){}) before it can be used for prototypical inheritance. You need something more like this:Here’s the deal: the property
prototypeworks together withnewby copying theprototypereference to the object (you can see what that entails by runningconsole.dir(aPerson)in Chrome console, for example). JavaScript checks the original object itself first, then prototype to see whether a function or property exists. That means you can change the reference prototypeagelater and see the changes reflected in the original object. Also, you can declare your ownagein the original object itself and have that override the prototype.