Play JavaScript OOP-class implementation _javascript tips

Source: Internet
Author: User
Tags inheritance

Overview

What are we talking about when we're talking about object-oriented programming?

The first thing we talk about are concepts: objects, classes, encapsulation, inheritance, polymorphism.

Objects and classes are object-oriented, and encapsulation, inheritance, and polymorphism are the three characteristics of object-oriented programming.

JavaScript provides objects but lacks classes, and it cannot explicitly define a class as C #.

But the function of JavaScript is very flexible, one of them is the constructor, combining constructors and prototype object can implement "class".

Concepts of objects and classes

Object

Object is a very important concept in object-oriented programming, an object is a description of "something" (a person or thing).

People and things are derived from the real life, our understanding of the real world is the cognition of people and things.

In the field of programming, code is abstract for ordinary people, and the application of code composition is to solve real world problems better.

In the analysis and design phase, the concept of "object" can be used to better reflect real-world problems.

On the other hand, the code contains some logic that describes the business, the business is comprised of business knowledge, and the business knowledge is summed up by the understanding and analysis of the real world, which is made up of "objects" in the real world.

Objects contain features and behavior, in OOP terms, features are attributes of objects, and behavior is the object's method.

Class

In the real world, similar objects can be grouped according to certain criteria. For example, "hummingbirds" and "eagles" are divided into birds, birds are not a specific object, it is based on the "Hummingbird", "Eagle" and other specific birds to analyze similar characteristics and behavior, summed up a concept. Class is equivalent to a template, we can create different concrete objects based on this template.

In C #, we can define a bird.

<summary>
///birds
///</summary> public
class Bird
{public
  void Fly ()
  {
    Console.WriteLine ("I can fly!");
  }

Although JavaScript is an object-oriented programming language, it does not provide class syntax support.

In JavaScript, everything is object-based, and even the "prototypes" that follow are objects, and JavaScript's inheritance and reuse is done through prototypes.

However, the combination of constructors and prototype objects enables the "class" of JavaScript.

Constructors

Before we used the new array () to create an array, we created an object with the new object (), array () and object () were two constructors built into JavaScript, although JavaScript did not provide classes. But we can interpret array and object as the concept of "class".

It should be noted that JavaScript's "class" is implemented by constructors.

Defining constructors

Constructors are also functions, and there is no grammatical difference between defining constructors and other functions.

The only difference is that the first letter of the constructor should be capitalized, which is also the programming specification for JavaScript.

The following defines a person () constructor, which we can interpret as the person class.

function person () {
	console.log (' I am keepfool. ');
}

JavaScript's "classes" and constructors are defined at the same time, and the constructor is defined while defining "class" in JavaScript.

Using constructors

JavaScript uses classes in the same way as C #, and the new keyword follows the constructor.

var p = new person ();

Defining Properties and methods

Now that we have defined the person class, you can add some properties and methods to the person class.

Defining attributes

When we talk about JavaScript objects, we talk about the object's property settings and access.
This code shows two ways to define an object's properties:

var cat = {
	color: ' Black '
};
Cat.name = ' Tom ';
Console.log (Cat.color);
Console.log (Cat.name);

Use this to define properties

The properties of the JavaScript class are defined differently, using the This keyword in the constructor to define the attributes:

function person (name) {
	this.name = name;
}

• The first line of code, defines the person class, and defines the constructor.

• The second line of code that defines the Name property.

Creating and working with objects

The following 2 lines of code create objects for two person classes

var p1 = new Person (' James ');
var p2 = new Person (' Cury ');

Output P1.name and P2.name in the Chrome console

P1 and P2 are two different objects, and modifying p1.name does not affect p2.name.

P1.name = ' Lebron James ';

Defining Methods

First, we distinguish between the terms "functions" and "methods", and "functions" are separate units, whereas "methods" are dependent on the existence of a class as a body.

Use this to define a method

In JavaScript, the method of a class is a function defined in a constructor that uses this keyword to define a method in a constructor:

function person (name) {
	//definition property
	this.name = name;
	Define method
	This.sayhello = function () {return
		' Hello, I am ' + this.name;
	}
}

How to use

The SayHello () method of calling P1 and P2 objects separately in the Chrome console

Constructor property

When an object is created, a special attribute is automatically assigned to the object by JavaScript, which is the constructor property.
In the chrome console p1.constructor , you can see that the constructor property of the P1 object points to a function.

Look at the contents of this function, isn't that the person () constructor?

This means that we can also create objects through the P1.constructor property.

var p3 = new P1.constructor (' Steve Nash ');

This line of code illustrates one sentence: "I don't care how the P1 object was created, but I want another object to be created like P1!" ”

Using the instanceof operator in the chrome console, you can see that P1, P2, and P3 are instances of the person class

Also, when we create an object in a {} way, we actually call the object () constructor.

var o = {};

This line of code declares an object, although we do not set any properties and methods, but the JavaScript engine defaults to it by setting the constructor property.
o.constructorpoints to the object () constructor, which [native code] shows that object () is a function built into JavaScript.

Prototype Object

In JavaScript, when you define a function, the function has the prototype attribute, and the constructor is no exception.
The following figure illustrates that the prototype property of the person () constructor is an object that is part of a function , and we call this property a prototype object.
from the point of view of the person class, we can also understand that the prototype property belongs to the person class.

At the same time the instance of the person class has no prototype attribute, and the P1.prototype on the above is undefined, which means that the prototype property is shared, somewhat like a static property in C #.

Set prototype

Since prototype is an object, you can add properties and methods to it.

Defining properties and methods on the Protpotype property of a function is no different from setting a normal object's properties and methods.
The following code defines the properties and methods for Person.prototype.

function person (name) {
	this.name = name;
	This.sayhello = function () {return
		' Hello, I am ' + this.name;
	}
}

Define properties and methods on the prototype object of the constructor
Person.prototype.height = 176;
Person.prototype.run = function () {return
	' I am ' + this.name + ', I am running! ';
}

var p1 = new Person (' James ');

Using prototype

The properties and methods defined in Person.prototype can be used directly by instances of the person class, and are still object.property used in the same way.

It is necessary to note that the name and sayHello() is an instance of the person class, height and is an instance that is run() not part of the person class.

Tip: You can see whether an object contains a property or method by using the hasOwnProperty method.

Properties of own vs. prototype

Instances of the person class can use properties in the person class as well as properties in Person.prototype.
What is the difference between the property of the person class and the Person.prototype property?

First, we can interpret the properties and methods in the person class as "instance properties."
Because prototype is shared, we can interpret the properties and methods in prototype as "shared properties."

The difference between an instance property and a shared property is primarily performance.
Each instance of creating a person creates a copy of the Name property and the SayHello () method, whereas the Height property and the run () method share a copy of all instances.

In this case, this means that the SayHello () method can refer to the prototype.
In addition, the height of a different person instance may not be the same, and it should be more reasonable to place it in the person class.

function Person (name,height) {
	this.name = name;
	this.height = height;
}

Person.prototype.sayHello = function () {return
	' Hello, I am ' + this.name + ', my # ' + this.height + ' cm. '; 
   }
Person.prototype.run = function () {return
	' I am ' + this.name + ', I am running! ';
}

var p1 = new Person (' James ', 203);
var p2 = new Person (' Cury ', 190);

Summary of implementation of the class

JavaScript has no classes, but constructors can implement "classes."

According to the JavaScript programming specification, the first letter of the constructor should be capitalized.

The properties and methods of the class are defined in the constructor in a this.property manner.

JavaScript assigns the constructor property to an object when the object is created, and the constructor property is a reference to the object constructor.

A function already has the prototype property when it is defined, and the prototype property is also an object.

Prototype are shared, and properties and methods defined on prototype can be used by instances of "classes".

If a property or method can be defined on a prototype, do not define on the constructor, using prototype can reduce the memory overhead.

The above play to JavaScript OOP-class implementation is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.