JavaScript definition classes (Class) Three ways to explain _javascript skills

Source: Internet
Author: User

Almost 20 years ago, when JavaScript was born, it was just a simple web scripting language. If you forget to fill in the username, it jumps out a warning.

Today, it becomes almost omnipotent, from the front end to the back end, with a variety of unthinkable uses. Programmers use it to accomplish increasingly large projects.

The complexity of JavaScript code also goes up in a straight line. A single Web page that contains 10000 of lines of JavaScript code has long been commonplace. 2010, an engineer revealed that Gmail's code length is 443000 lines!

To write and maintain such complex code, you must use a modular strategy. At present, the industry's mainstream approach is to adopt "object-oriented programming." Therefore, how to achieve object-oriented programming JavaScript, has become a hot topic.
The trouble is that the JAVASCIPT syntax does not support "class", resulting in traditional object-oriented programming methods that cannot be used directly. Programmers have done a lot of exploring how to simulate "classes" with JavaScript. This paper summarizes the three methods of JavaScript definition "Class", discusses the characteristics of each method, and emphatically introduces the best method in my eyes.

==============================================

Three ways for JavaScript to define classes (class)

In object-oriented programming, classes (Class) are templates of objects (object) that define properties and methods that are common to the same set of objects (also known as "instances").

The JavaScript language does not support "classes," but you can simulate "classes" in some alternative way.

First, the structural function method

This is the classical method, is also the textbook must teach the method. It simulates "class" with the constructor, and within it uses the This keyword to refer to the instance object.

Copy Code code as follows:

function Cat () {
THIS.name = "hairy";
}

When you generate an instance, use the New keyword.
Copy Code code as follows:

var cat1 = new Cat ();
alert (cat1.name); Nagymaros

Class, and can also be defined on top of the prototype object of the constructor.

Copy Code code as follows:

Cat.prototype.makeSound = function () {
Alert ("Meow meow Meow");
}

For a detailed description of this approach, please see my series of articles "Javascript object-oriented programming", here is not much to say. Its main disadvantage is that it is more complex to use this and prototype, writing and reading are laborious.

Second, object.create () Law

In order to solve the disadvantage of "constructor method", more easily generate objects, JavaScript International standard ECMAScript Fifth edition (currently in the third edition), proposed a new method Object.create ().
In this way, "class" is an object, not a function.

Copy Code code as follows:

var Cat = {
Name: "Hairy",
Makesound:function () {alert ("Meow Meow");}
};

Then, you generate the instance directly with Object.create () without using new.

Copy Code code as follows:

var cat1 = object.create (Cat);
alert (cat1.name); Nagymaros
Cat1.makesound (); Meow Meow Meow

This method is currently deployed in the latest versions of the major browsers, including IE9. If you encounter an older browser, you can deploy it yourself with the following code.

Copy Code code as follows:

if (! Object.create) {
Object.create = function (o) {
function F () {}
F.prototype = O;
return new F ();
};
}

This method is simpler than "constructor method", but it can't realize private property and private method, the instance object can not share data, and the simulation of "class" is not comprehensive enough.

Iii. Minimalist Approach

The Dutch programmer, Gabor de Mooij, proposed a better new approach than object.create (), which he called the "minimalist approach" (minimalist approach). This is also the method I recommend.

3.1 Package

This method does not use this and prototype, and the code is very simple to deploy, which is probably why it is called the minimalist approach.

First, it also simulates "class" with an object. Within this class, define a constructor createnew (), which is used to generate the instance.

Copy Code code as follows:

var Cat = {
Createnew:function () {
Some code here
}
};

Then, in CreateNew (), define an instance object that takes the instance object as the return value.

Copy Code code as follows:

var Cat = {
Createnew:function () {
var cat = {};
Cat.name = "hairy";
Cat.makesound = function () {alert ("Meow Meow");};
return cat;
}
};

When used, the CreateNew () method is invoked, and the instance object can be obtained.

Copy Code code as follows:

var cat1 = Cat.createnew ();
Cat1.makesound (); Meow Meow Meow

The advantage of this approach is that it is easy to understand, the structure is clear and elegant, consistent with the traditional "object-oriented programming" constructs, so the following features can be easily deployed.

3.2 Inheritance

It is convenient to have one class inherit from another. As long as in the former CreateNew () method, the CreateNew () method of the latter is invoked.

Define a animal class first.

Copy Code code as follows:

var Animal = {
Createnew:function () {
var animal = {};
Animal.sleep = function () {alert ("Sleep Late");};
return animal;
}
};

Then, in the Cat CreateNew () method, the animal CreateNew () method is invoked.

Copy Code code as follows:

var Cat = {
Createnew:function () {
var cat = Animal.createnew ();
Cat.name = "hairy";
Cat.makesound = function () {alert ("Meow Meow");};
return cat;
}
};

This results in a cat instance that inherits both the cat class and the animal class.
Copy Code code as follows:

var cat1 = Cat.createnew ();
Cat1.sleep (); Sleep

3.3 Private properties and private methods

In the CreateNew () method, as long as the methods and properties that are not defined on the Cat object are private.

Copy Code code as follows:

var Cat = {
Createnew:function () {
var cat = {};
var sound = "Meow meow meow";
Cat.makesound = function () {alert (sound);};
return cat;
}
};

The internal variables of the example above are sound and cannot be read externally, only read by the public method of cat MakeSound ().
Copy Code code as follows:

var cat1 = Cat.createnew ();
alert (Cat1.sound); Undefined

3.4 Data sharing

Sometimes, we need all instance objects to be able to read and write the same internal data. This time, as long as the internal data, encapsulated within the class object, CreateNew () method outside.

Copy Code code as follows:

var Cat = {
Sound: "Meow meow Meow",
Createnew:function () {
var cat = {};
Cat.makesound = function () {alert (cat.sound);};
Cat.changesound = function (x) {cat.sound = x;};
return cat;
}
};

Then, two instance objects are generated:

Copy Code code as follows:

var cat1 = Cat.createnew ();
var cat2 = Cat.createnew ();
Cat1.makesound (); Meow Meow Meow

At this point, if you have an instance object that modifies the shared data, another instance object can also be affected.
Copy Code code as follows:

Cat2.changesound ("La la La");
Cat1.makesound (); La La la

Finish

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.