"Class" Inheritance and prototype inheritance in JS

Source: Internet
Author: User

Class Inheritance:

A "class" Student was created with the function constructor, and a method SayHello was defined on the Student prototype, then a "class" Primarystudent was created, and the primarystudent was initialized with apply ().

Then let the prototype of primarystudent equal to the object created by student, and point the constructor on the Primarystudent prototype to the current "class", i.e. Primarystudent, and note the red bold part.

1 functionStudent (name) {2      This. Name =name;3 }4Student.prototype.sayHello =function(){5Console.log ( This. Name);6 }7 functionprimarystudent (name) {8Student.apply ( This, arguments);9 }Ten primarystudent.prototype = new Student ();  OnePrimaryStudent.prototype.constructor =primarystudent; A varStu =NewPrimarystudent ("Yxz"); -Stu.sayhello ();//Output YXZ

Prototype Inheritance:

The key difference between prototype inheritance and "Class" Inheritance lies in the red bold part below, where an empty function f is defined, then the prototype prototype of student is assigned to the prototype prototype of F, and then

Execute Primarystudent.prototype = new F ().
1 functionStudent (name) {2      This. Name =name;3 }4Student.prototype.sayHello =function(){5Console.log ( This. Name);6 }7 varF =function(){8 9 }Ten functionprimarystudent (name) { OneStudent.apply ( This, arguments); A } - F.prototype = student.prototype;14 Primarystudent.prototype = new F (); thePrimaryStudent.prototype.constructor =primarystudent; - varStu =NewPrimarystudent ("Yxz"); -Stu.sayhello ();

"Class" Inheritance and prototype inheritance in JS

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.