How JavaScript implements Inheritance

Source: Internet
Author: User

Functions in JavaScript are omnipotent, and in addition to the function definitions used, they can be used for the definition of a class. JavaScript inheritance, it is also a bit strange to say, there is no public,private such as access control decoration, there is no implement or other specific symbols to illustrate is the implementation of inheritance. Refer to the following example for the inheritance of JavaScript classes. Dancheng Shu Marine Environmental protection

01 <script type="text/javascript">
02 functionPerson() {
03     // 属性
04     this.Gender = "female";
05     this.Age = 18;
06     this.Words = "Silence";
07     // 方法
08     this.shouting = function() {
09         alert("开心哦!父类的方法");
10     }
11 }
12 // 继承
13 functionProgrammer() {
14     this.base = Person;
15 }
16 Programmer.prototype = newPerson;
17 // 为子类添加新的方法
18 Programmer.prototype.typeCode = function() {
19     alert("俺是敲代码的!IT民工,很不开心。子类的方法");
20 }
21 // 调用示例
22 functionsayHello() {
23     vara = newProgrammer();
24     alert(a.Gender); // 调用父类的属性
25     a.shouting(); // 调用父类的方法
26     a.typeCode(); // 调用子类的方法
27 }       
28 sayHello();
29 </script>
Simulating classes and inheritance in JavaScript

In object-oriented languages, we use classes to create a custom object. While everything in JavaScript is an object, what is the way to create a custom object?

This requires the introduction of another concept-prototype (prototype), we can simply think of prototype as a template, the newly created custom object is a copy of the template (prototype) (actually not a copy but a link, but the link is not visible, It feels like a copy to the people.

Let's take a look at an example of creating a custom object through prototype:

01 // 构造函数
02 functionPerson(name, sex) {
03     this.name = name;
04     this.sex = sex;
05 }
06 // 定义Person的原型,原型中的属性可以被自定义对象引用
07 Person.prototype = {
08     getName: function() {
09         returnthis.name;
10     },
11     getSex: function() {
12         returnthis.sex;
13     }
14 }

Here we refer to the function person as the constructor, which is the function that creates the custom object. As you can see, JavaScript simulates the functionality of a class by constructing functions and prototypes.

Code to create a custom object (instantiation Class):

1 varzhang = newPerson("ZhangSan""man");
2 console.log(zhang.getName()); // "ZhangSan"
3 varchun = newPerson("ChunHua""woman");
4 console.log(chun.getName()); // "ChunHua"

When code var Zhang = new person ("Zhangsan", "man") executes, there are actually several things that are done internally:

    1. Creates a blank object (new Object ()).
    2. Copy the attributes in Person.prototype (key-value pairs) into this empty object (as we mentioned earlier, the internal implementation is not a copy but a hidden link).
    3. Pass the object through the This keyword to the constructor and execute the constructor.
    4. Assign this object to the variable Zhang.

To prove that the prototype template is not copied to the instantiated object, but rather a link, see the following code:

01 functionPerson(name, sex) {
02     this.name = name;
03     this.sex = sex;
04 }
05 Person.prototype.age = 20;
06 varzhang = newPerson("ZhangSan""man");
07 console.log(zhang.age); // 20
08 // 覆盖prototype中的age属性
09 zhang.age = 19;
10 console.log(zhang.age); // 19
11 deletezhang.age;
12 // 在删除实例属性age后,此属性值又从prototype中获取
13 console.log(zhang.age); // 20

This hidden prototype link, implemented within JavaScript, is the moist soil that JavaScript relies on to survive, and is the basis for the simulation of inheritance.

How do I implement simple inheritance in JavaScript?

The following example creates an employee class employee, which inherits all the properties from the prototype prototype from person.

01 functionEmployee(name, sex, employeeID) {
02     this.name = name;
03     this.sex = sex;
04     this.employeeID = employeeID;
05 }
06 // 将Employee的原型指向Person的一个实例
07 // 因为Person的实例可以调用Person原型中的方法, 所以Employee的实例也可以调用Person原型中的所有属性。
08 Employee.prototype = newPerson();
09 Employee.prototype.getEmployeeID = function() {
10     returnthis.employeeID;
11 };
12 varzhang = newEmployee("ZhangSan""man""1234");
13 console.log(zhang.getName()); // "ZhangSan

The above implementation of inheritance is coarse, and there are many problems:

    • It is not appropriate to instantiate a person when creating an employee constructor and prototype (hereafter referred to as a class).
    • The constructor of the employee cannot invoke the constructor of the parent class person, resulting in a duplicate assignment of the name and sex attributes in the employee constructor.
    • The function in the employee overrides the function with the same name in person, without overloading the mechanism (and the previous one is a type of problem).
    • The syntax for creating JavaScript classes is too fragmented to be as elegant as the syntax in C#/java.
    • The implementation has a pointing error in the constructor property.

How JavaScript implements Inheritance

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.