Reputation: 339
<script type="text/javascript">
var Person =
{
Create: function(name, age) {
this.name = name;
this.age = age;
},
showMe: function() {
return " Person Name: " + this.name + " Age: " + this.age + " ";
}
};
function New(aClass, aParams) {
function new_() {
aClass.Create.apply(this, aParams);
};
new_.prototype = aClass;
var obj = new new_();
return obj;
}
</script>
I don't quite understand the code above. Could someone tell me the meanings of Person, Create, showMe, New and new_? Thanks a lot.
Upvotes: -1
Views: 169
Reputation: 11332
Person
is an object with two functions - Create
and showMe
. In JavaScript, there are no classes, only objects, and this is how you write up an object - using 'Object Literal Notation' (the curly braces and functions/properties separated by commas).
New
is a clever re-implementation of the new
keyword. Instead of classes, javascript has prototypes, and instead of creating an instance of a class you create a copy of the prototype. In this case, if you passed Person
to New()
, it would used as the prototype in new_.prototype = aClass
, and the rest of this function will return an object with the Person
prototype, which means any changes to Person
later on will be inherited into obj
as well (unless obj
has overridden them).
Upvotes: 2
Reputation: 16788
`Person` -- a variable w/ 'parts' (used loosely) `Person.Create` and `Person.showMe'
`Person.Create` -- function of `Person` that sets `Person.name` and `Person.age` to its arguments
`Person.showMe` -- returns a string explaining values of `Person.name` and `Person.age`
`New` -- a function intended to instantiate new Person's thru prototypal (this is NOT class based) inheritenced
`New._new` -- `New` uses this to get it done
Basically thru prototype inheritence, even though Person
is only 'made' once, other 'versions' of it can be constructed in kind. It can be used like this (try it here: http://jsfiddle.net/PBhCs/)
var Person = {
Create: function(name, age)
{
this.name = name;
this.age = age
},
showMe: function()
{
return " Person Name: " + this.name + " Age: " + this.age + " ";
}
};
function New(aClass, aParams)
{
function new_()
{
aClass.Create.apply(this, aParams);
};
new_.prototype = aClass;
var obj = new new_();
return obj;
}
var a = New(Person, ['moo', 5]);
var b = New(Person, ['arf', 10]);
alert(a.showMe() + b.showMe());
Upvotes: 0