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(开发者_如何学JAVAaPerson .age);
});
Why cant I do this?
Person
is only declared as part of your aPerson
variable, 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:
// Create a Person function object
function Person() {
};
// Modify that function's prototype
Person.prototype.age = 22;
$(document).ready(function() {
// aPerson.__proto__ = Person.prototype
var aPerson = new Person();
// JS checks whether aPerson has age already set, if not, it checks
// aPerson's prototype -- in which case it's given the value 22
alert(aPerson.age);
});
Here's the deal: the property prototype
works together with new
by copying the prototype
reference to the object (you can see what that entails by running console.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 prototype age
later and see the changes reflected in the original object. Also, you can declare your own age
in the original object itself and have that override the prototype.
I'm quite certain you have to reference your function using aPerson
rather than Person
(externally). Internally, you'd reference it using Person
.
Alternatively, you could do this -
function Person() {
}
var aPerson = new Person();
$(function() {
Person.prototype.age = 22;
alert(aPerson.age) //22
});
because aPerson
doesn't have an age. You will have to call new
for it to work.
var aPerson = function Person(){
};
$(document).ready(function(){
Person.prototype.age = 22;
bPerson = new Person();
window.alert(bPerson.age);
});
精彩评论