Pseudo class
// Constructor call mode
VaR mammal = function (name)
{
This. Name = Name;
};
Mammal. Prototype. get_name = function ()
{
Return this. Name;
};
Mammal. Prototype. Says = function ()
{
Return this. Saying | '';
};
VaR cat = function (name)
{
This. Name = Name;
This. Saying = 'meow ';
};
Cat. Prototype = new mammal ();
Cat. Prototype. Purr = function (n ){
VaR I, S = '';
For (I = 0; I <n; I ++)
{
If (s)
{
S + = '-';
}
S + = 'R ';
}
Return S;
};
Cat. Prototype. get_name = function ()
{
Return this. Says () + ''+ this. Name +'' + this. Says ();
};
VaR MyCat = new CAT ('henrietta ');
VaR says = MyCat. Says ();
VaR purr = MyCat. Purr (5 );
VaR name = MyCat. get_name ();
// The above pseudo-class pattern looks strange. We can hide some ugly details.
// Use the method to define an inherits Method for implementation
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Function.method('inherits', function(Parent){
this.prototype = new Parent();
return this;
});
var Cat = function(name)
{
this.name = name;
this.saying = 'meow';
}.inherits(Mammal).method('purr',function(n){
var i, s = '';
for(i = 0; i < n; i ++)
{
if(s)
{
s += '-';
}
s += 'r';
}
return s;
}).method('get_name', function(){
return this.says() + ' ' + this.name + ' ' + this.says();
});
// The code above has constructor functions similar to "class", but it does not have a private environment and all attributes are public. The method of the parent class cannot be accessed.
// If new is not used during the call, this will be bound to the global object, so not only the new object is not expanded, but the global variable is destroyed.