"Translate" 3 ways to define a JavaScript class

Source: Internet
Author: User
Tags types of functions

This article really does not have any difficulty, I am in order to test my English level degenerated not haha although my English originally had the dregs to translate also like plain English. Will read the original version of the code after the translation of almost one hours, in which the comments are part of their own understanding of the omission or misunderstanding is also grateful to the place, such as JavaScript in the understanding of a single example of the sense of the definition of a vague ah.

Translated from the original Stoyan Stefanov link: http://www.phpied.com/3-ways-to-define-a-javascript-class/

Introduction

JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways to define and instantiate an object. Even if you've already used some of the ways you like it, the following introduction helps you learn some other ways to help you read someone else's code.

It is important to note that there is no concept of class in JavaScript, but by using Function You can emulate a class, where everything in JavaScript is object, and in terms of inheritance, objects inherit objects rather than class-inheriting classes.

1. Use function

This is probably the most versatile way to define a JavaScript function and then pass  new The   keyword Creates an instance object, through which the Function,    keyword to add properties and methods to this instance object. Here is an example.

function Apple (type) {   this. Type = type;     this. Color = "Red";    this. getInfo = getappleinfo;} // anti-pattern! (anti-pattern) Keep reading ... function Getappleinfo () {   returnthis this. Type + ' Apple ';}

This object instance is created using the Apple constructor function, adding some properties and then calling some methods, continue to see:

var New Apple (' macintosh '= ' reddish '; alert (Apple.getinfo ());

1.1. Method definition in the internal

In the example above we see that the GetInfo method of the Apple "class" is separated and defined as function getappleinfo () . This looks like a good job, but there's a downside-you might end up defining many types of functions, all in the "global namespace." This means that when you create another function (or use a different library) with the same name, a naming conflict occurs. To prevent this, you can define the method inside the constructor function, like this:

function Apple (type) {   this. Type = type;     this. Color = "Red";     This function () {      returnthis this. Type + ' Apple ';   }}

This syntax creates an instance with no difference from the previous.

1.2. Method is added on the prototype attribute

There are still drawbacks in the 1.1 approach, and each time a new instance is created the getInfo () method is added to the instance object each time. Sometimes this may not be what you want, an effective way to add getInfo () is to define it on the stereotype property of the constructor.

function Apple (type) {   this. Type = type;     this. Color = ' Red 'function() {   returnthis this . Type + ' Apple ';};

Can be used in the same way as 1. and 1.1.

2. Using the object self-polygon amount

Object literals in JavaScript are a fast, streamlined way to define an object instance or an array instance, in order to create an empty object you can:

var o = {};

Instead of a common approach:

var New Object ();

To create an array instance you can:

var a = [];

To replace:

var New Array ();

In this way you can skip the class and create an instance immediately (object). The following is still described in the previous example, this time using the object literal syntax:

var apple = {   "Macintosh",   "Red",   function  () {        return  This this. Type + ' Apple ';   }}

In this way you do not have to create an instance from the class because the instance object already exists and you just need to use it:

Apple.color = "reddish"; alert (Apple.getinfo ());

This instance is sometimes called a singleton, and in some typical languages such as Java, a singleton means that you can only have a single instance of a class at any time, and you cannot create more instance objects from the same class. But this concept is meaningless in JavaScript because all objects start with a single case (annotation: The largest native object in JavaScript is object, which is both a constructor and a function,array, and the other native objects are also , so JavaScript implements single-case inheritance of Singleton?? , you can create a self-polygon volume object at any time).

3. Using a singleton in a function

The third way is the combination of the first two, you can use the function to define a singleton object, which is the syntax:

var New function () {    this. Type = "Macintosh";      this. Color = "Red";      This function () {       returnthis this. Type + ' Apple ';    }}

This definition is very similar to 1.1, similar to 2 on the use of instance objects.

Apple.color = "reddish"; alert (Apple.getinfo ());

New function() {...} Two things are done: Define a function (the anonymous constructor) and invoke it with new . This may seem a little confusing if you haven't used it before, but it's a good choice when you really need a constructor and only use it once and don't have to give it a name. (annotations: This seems like a neat way to look, because you specify a type for the singleton, remember that the "elevation" in the case of the specified type is called "Enhanced module Mode", for this example, the use of the following:

var function () {    varnew  Apple ();     return obj;} ();

Summarize

There are three ways to create instance objects, JavaScript is not defined as a class, it's a magical language ...

"Translate" 3 ways to define a JavaScript class

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.