Javascript: inheritance (1)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.