JS Native Design Pattern--2 object-oriented programming inheritance-new class inheritance

Source: Internet
Author: User

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>classInherit</title>
<script type= "Text/javascript" >
Declaring a parent class
Function Superclass () {
this.name = ' Lucy ';
}
SuperClass.prototype.getName = function () {
Console.log (this.name);
}
Declaring a subclass
function Subclass () {
This.subname = ' Lilei ';
This.books = [' html ', ' CSS ', ' JS '];
}
Class-Type Inheritance
Subclass.prototype = new superclass ();
Note: You must first inherit, and then add the subclass prototype method, otherwise the subclass of the instance calls the subclass prototype method will be error: function is not defined
SubClass.prototype.getSubName = function () {
Console.log (This.subname);
}
The prototype prototype constructor property of the subclass is fixed to the subclass subclass, otherwise the inheritance defaults to the prototype of the parent class, which can cause problems
SubClass.prototype.constructor = subclass;
Instantiating an Object test
var test1 = new Subclass ();
var test2 = new Subclass ();
Console.log (Test1.name); Lucy
Console.log (Test1.subname); Lilei
Test1.getname (); Lucy
Test1.getsubname (); Lilei
Console.log (Test1.books);
Test1.books.push (' php ');
Console.log (Test1.books); Output: ["HTML", "CSS", "JS", "PHP"]
Console.log (Test2.books); Output: ["HTML", "CSS", "JS"]
No impact between two instances
This example has passed validation
</script>
<body>

</body>

JS Native Design Pattern--2 object-oriented programming inheritance-new class inheritance

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.