I've always seen that the preferred alternative to
function MyObject ( ... )
{
this.MyFunction = function ( ... ) { ... }
// ...
}
is
function MyObject ( ... )
{
// ...
}
MyObject.prototype.MyFunction = function ( ... ) { ... }
My understanding is that in the way that the JavaScript hierarchy known as the prototype chain works, MyObject.prototype
is the object from which MyObject
derives. In English, what this is saying is
"Give me a property by giving it to my ancestor who I will then inherit it from."
which seems like a very obscure and inefficient way of going about things. Coming from a C# background, how I see this is like the equivalent of having a class
class SpecialString : String
{
}
and saying
Ok, I want
SpecialString
to have a functionSpecialFunction
, so I'll go intoString
and give itpublic void SpecialString (...)
. NowSpecialString
has it! Mission accomplished.