Javascript object-oriented 4 inheritance _ js object-oriented

Source: Internet
Author: User
Inheritance is an essential feature of object-oriented systems, but javascript does not have an inherited conceptual mechanism, but we can implement this function on our own. The Code is as follows:


Var JsObject ={}| | new Object ();
JsObject. extend = function (subClass, superClass ){
// First determine whether the subClass has been defined. If not defined, the class is redefined.
If (typeof subClass = "undefined") subClass = function (){};
// If the parent class superClass is a class, it is converted to an object
If (typeof superClass = "function") superClass = new superClass ();
// Traverse the attributes and methods in the parent class superClass object
For (var p in superClass)
{
/* Copy the attributes and methods in the parent class superClass object to the prototype object of the subclass,
Therefore, subclass has all the features of the parent class, that is, inheritance */
SubClass. prototype [p] = superClass [p];
}
Return subClass;
};
Function Student ()
{
This. name = "James ";
This. updateName = function (name ){
This. name = name;
}
}
Function Class1 ()
{
This. sex = "male ";
This. updateSex = function (sex ){
This. sex = sex;
}
}
// Define the class Class1 to inherit the Student class
Class1 = JsObject. extend (Class1, Student );
Var obj = new Class1 ();
Alert (obj. sex );
Alert (obj. name );
Obj. updateSex ("female ");
Obj. updateName ("Mary ");
Alert (obj. sex );
Alert (obj. name );


The results show that male, Michael, female, and Mary
Related Article

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.