JS Object-Oriented Programming small note

Source: Internet
Author: User

JavaScript Object-oriented programming in the concept of classification and instance, but through the prototype to achieve object-oriented programming.

var Student = {

Name: ' Robot ',

height:1.6,

Run:function () {

Console.log (THIS.name + ' is running ... ');

}

};

var xiaoming = {

Name: ' Xiaoming '

}

xiaoming.__proto__ = Student; Xiaoming's prototype pointed to student,xiaoming inherited the student attribute.

Xiaoming has its own name property but does not have a run () method, and because Xiaoming inherits student, Xiaoming can invoke it as long as the student has the run () method. Xiaoming can become any object while the code is running

When actually writing JavaScript code, don't use obj.__proto__ to change the prototype of an object directly. Object.create () can pass in a prototype object and create a new object based on that prototype, but none of the new objects have any properties. You can write a function to create a xiaoming

function Createstudent (name) {

s = object.create (Student); Create a new object based on the student prototype

S.name = name;//Initializes a new object

return s

}

var xiaoming = createstudent ("Xiaoming");

Xiaoming.run ();//xiaoming is running ...

xiaoming.__proto__ = Student;//true

The above is a way to create a prototype inheritance.

JavaScript sets a prototype object to each created object, in addition to using {...} directly. To create an object, JavaScript can also create an object from the constructor's method

function Student (name) {this.name = name;        This.hello:function () {alert (' Hello ' + this.name + '! '); }    }

This function can use the new keyword to invoke and return an object

var xiaoming = new Student (' xiaoming '); xiaoming.name;//' Xiao Ming ' Xiaoming.hello (); Hello, Xiaoming!

Note that if you do not write new, it is a normal function that returns undefined by default. If you write new, it is the constructor that binds this to the newly created object and returns the this by default, so you do not need to write return this later.

The prototype chain for the newly created Xiaoming is

Xiaoming-----> Student.prototype----->object.prototype-----> Null

The object created with new Student () also obtains the constructor property from the prototype, which points to the function Student itself

Xiaoming.constructor = = = Student.prototype.constructor;//true Student.prototype.construcror = = = Student;//true Objec T.getprototypeof (xiaoming) = = = Student.prototype;//true xiaoming instanceof student;//true

note that the Hello () method of many objects created by new Student () Here is not equal, in fact the Hello function of these objects only needs to share the same one. Modify the code as follows

function Student (name) {this.name = name;    } Student.prototype.hello = function () {alert (' Hello, ' + this.name + '! '); };

This is the way to create a prototype-based JavaScript object with new.

Call constructor do not forget to write new, because in use strict mode this.name = Name will be error, this binding is undefined; in non-strict mode, this.name = name does not error, this binding is window , the global variable name is created and the undefined is returned. In order to differentiate between constructors and ordinary functions, the first letter of the constructor should be capitalized, and the first letter of the normal function should be lowercase.

We can write a createstudent () function that encapsulates all of the new operations internally. A common pattern is as follows

    function student (props)  {         this.name = props.name | |   ' unamed ';//default value is Unamed        this.grade = props.grade  | |  1;//Default value is 1    }    student.prototype.hello = function   ()  {        alert  (' hello,  '  +  this.name +  '! ');         }    function createstudent (props)  {        return new student (props | |  {})     }    var xiaoming = createstudent ({         name:  ' Xiao Ming '     });     XIAOMING.GRADE;//1 

There are several great advantages to this createstudent (): One is not to call through new, and the other is very flexible and can not be passed.

JavaScript prototype inheritance:

In traditional class-based languages such as Java and C + +, the essence of inheritance is to extend an existing class and generate new subclass.

Because such languages strictly differentiate between classes and instances, inheritance is actually an extension of the type. However, because of the prototype inheritance of JavaScript, we cannot extend a class directly because there is no such type as class.

Write a constructor first

function Student (props) {this.name = Props.name | |    ' Unamed ';    } Student.prototype.hello = function () {alert (' Hello, ' + this.name + '! '); };

Now to extend the primarystudent based on the student, define Primarystudent first

function Primarystudent (props) {//Call Student constructor, bind this variable student.call (this,props); This.grade = Props.grade | |    1; }

But the prototype chain that called the student constructor does not equal the inheritance student,primarystudent is

New primarystudent ()----> Primarystudent.prototype-----> Object.prototype----> Null

To find a way to modify the Primarystudent prototype chain to

New Primarystudent ()----->primarystudent.prototype----->student.prototype----->object.prototype----- >null

The intermediate object can be used to implement the correct prototype chain, the prototype of this intermediate object points to Student.prototype, the intermediate object can use an empty function to implement

function F () {}
The prototype of F points to student.prototype f.prototype = Student.prototype;
Point the Prototype object of Primarystudent to the new F object, and the prototype of the F object points to student.prototype Primarystudent.prototype = new F ();
Fix the Primarystudent prototype's constructor to primarystudent PrimaryStudent.prototype.constructor = primarystudent;
Continue to define the method on the Primarystudent prototype (that is, new F ()) PrimaryStudent.prototype.getGrade = function () {return this.grade};
Create xiaoming var xiaoming = new Primarystudent ({name: ' Xiaoming ', grade:3}); xiaoming.name;//"Xiao Ming" xiaoming.grade;//3
Verify prototype xiaoming.__proto__ = = = Primarystudent.prototype;//true Xiaoming.__proto__.__proto__ = = = Student.prototype;//t Rue
Validating inheritance Relationships xiaoming instanceof primarystudent;//true xiaoming instanceof student;//true

If you enclose the inherited action in a inherit function, you can also hide the definition of f and simplify the code

function inherits (Child, Parent) {var F = function () {};        F.prototype = Parent.prototype;        Child.prototype = new F (); Child.prototype.constructor = child;}

This inherit () function can be reused

    function student (props)  {         this.name = props.name | |   ' Unnamed ';     }    student.prototype.hello = function   ()  {        alert (' hello,  '  + this.name  +  '! ');     }    function primarystudent (props)  {         student.call (This, props);             this.grade = props.grade | |  1;    }    //  implementing a prototype inheritance chain:     inherits ( Primarystudent, student);    //  bind other methods to primarystudent prototype:     primarystudent.prototype.getgrade = function  ()  {         return this.grade;    }; 

Summary , JavaScript's prototype inheritance is implemented in the following way:

1, define a new constructor, and call () internally invoke the constructor that you want to "inherit", and bind this;

2, using the intermediate function f to achieve the inheritance of the prototype chain, it is best to encapsulate the inherits function to complete;

3, continue to define the new method on the prototype of the new constructor.

Class Inheritance:

The New keyword class was formally introduced into JavaScript from ES6, and class was designed to make it easier to define classes.

If you write student with the new class keyword, you can write this

Class Student {Constructor (name) {this.name = name;        } hello () {alert (' Hello, ' + this.name + '! '); }    }

By comparison, you can see that the definition of class contains the constructor constructor and the function hello () defined on the prototype object (note that there is no function keyword), thus avoiding Student.prototype.hello = function () {...} Such a decentralized code.

Another great benefit of defining objects with class is that inheritance is more convenient. Think about the amount of code that we derive from student a primarystudent need to write. Now, the prototype inherits the intermediate object, the prototype object constructor and so on no need to consider, directly through the extends to realize

Class Primarystudent extends Student {constructor (name, grade) {super (name);//Remember to use super to call the parent class constructor Method!        This.grade = grade;        } mygrade () {alert (' I am at grade ' + This.grade); }    }


JS Object-Oriented Programming small note

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.