Object-oriented (object-oriented) programming in JavaScript

Source: Internet
Author: User
This article was originally published on my personal blog and has been revised and posted on csdn for the purpose of backup. For a better reading experience, please read it on my personal blog.

Recently, I have been using nodejs for development. With nodejs, the front end, back end, and script can all be done with javascript, which is very convenient. However, many syntaxes of JavaScript, such as objects, are different from our commonly used object-oriented programming languages; looking at a JavaScript open source project, you will often see the use of this keyword, and this keyword in JavaScript because of different context The meaning is different; there are strange prototype chains. These bits and pieces can easily be overwhelming, so it is necessary to have a deep understanding of the language javascript.

In this article, I mainly want to talk about how to do object-oriented programming in JavaScript, and at the same time, I will talk about some of the concepts of the JavaScript language at the beginning of the design. Let's start now.
First of all, let ’s emphasize that the javascript that we widely use now follows the ECMAScript 5.1 standard. The version under development is 6.0. This version has changed a lot, and many new syntaxes and functions have been added. .

design concept
javascript1.0 was originally developed by Netscape ’s Brendan Eich in May 1995 for ten days. Eich ’s goal was to design a language that was lightweight and powerful, so Eich took full advantage of other programming languages Features such as Java's syntax, Scheme's functions, Self's prototypal inheritance, Perl's regular expressions, etc.
It is worth mentioning that why is inheritance borrowed from the prototype mechanism of Self language rather than Java's class mechanism? First we must know:
-Self's prototype mechanism relies on runtime semantics
-Java's class mechanism relies on compile-time class syntax

The function of Javascript 1.0 is relatively simple. In order to continue to enrich the functions of javascript itself while maintaining the compatibility of old code in the future, javascript adds new functions by changing the support of the runtime, instead of modifying the syntax of javascript, which guarantees the old Code compatibility. This is why JavaScript chooses a prototype mechanism based on runtime.
Wikipedia describes it this way: JavaScript is classified as a prototype-based scripting language with dynamic typing and first-class functions. These features make JavaScript a multi-paradigm interpretive programming language that supports object-oriented, imperative, and functional programming styles.

Object
In javascript, except for simple types such as numbers, strings, Boolean values (true / false), and undefined, everything else is an object.
Simple types such as numbers, strings, and Boolean values are immutable. Objects are mutable keyed conllections. Objects include array Array, regular expression RegExp, function Function. Of course, Object is also an object.
Objects in JavaScript are a series of key-value pairs. The key can be any string, including an empty string; the value can be any value other than undefined. There is no class-free concept in JavaScript, but it has a prototype linkage. The javascript object implements the inheritance relationship through this chain.

There are some predefined objects in javascript, such as Object, Function, Date, Number, String, Array, etc.

Literal
Each type of object in javascript can be created literally.
For Object objects, you can use Object literal to create, for example:

var empty_object = {}; // An empty object is created
// Create an object with two attributes
var stooge = {
    "first-name": "Jerome",
    "last-name": "Howard"
};
Of course, you can also use new Object () or Object.create () to create objects.
The Function and Array objects have their corresponding literal forms, which will be described later, and will not be repeated here.

Prototype linkage
Each object in javascript implicitly contains a [[prototype]] attribute, which is the notation in ECMAScript. At present, the major browser manufacturers use the notation __proto__ when implementing their own JavaScript interpreter, This means that each object implicitly contains a __proto__ attribute. for example:

var foo = {
    x: 10,
    y: 20
};
The storage structure of the object foo in memory is roughly like this:

When there are multiple objects, a prototype chain can be formed through the __proto__ attribute. See the example below:

var a = {
    x: 10,
    calculate: function (z) {
        return this.x + this.y + z;
    }
};
var b = {
    y: 20,
    __proto__: a
};
var c = {
    y: 30,
    __proto__: a
};
// call the inherited method
b.calculate (30); // 60
c.calculate (40); // 80
When the above code declares objects b and c, it indicates that their prototype is object a (the prototype of a points to Object.prototye by default, and the prototype of Object.prototype points to null). Is such that:


It needs to be explained here. If we want to specify its prototype when declaring an object, we generally use the Object.create () method, which is more efficient.
In addition to the __proto__ attribute we are talking about here, I believe that everyone is more commonly the prototype attribute. For example, if there is no function to add a few days to the Date object, then we can do this:

Date.prototype.addDays = function (n) {
    this.setDate (this.getDate () + n);
}
Then all Date objects will have the addDays method in the future (explaining inheritance will explain why later). So what is the difference between the __proto__ attribute and the prototype attribute?

Every object in JavaScript has a __proto__ attribute, but only function objects have a prototype attribute.

So in a function object, what is the difference between these two properties?
1. __proto__ represents the prototype of the function object
2. prototype means that when new is used to execute the function (this function generally becomes a constructor, which will be explained later), the prototype of the newly created object. E.g:
var d = new Date ();
d.proto === Date.prototype; // here is true

Seeing this, I hope you can understand the difference between these two attributes.
In javascript, prototypes and functions are the two most important concepts. After talking about prototypes above, let's talk about function objects.

Function object
First of all, a function is nothing more than an object in JavaScript. It can be assigned to a variable as a value. The only difference is that the function can be executed.
The __proto__ property of an object created using object literals points to Object.prototype (the __proto__ property of Object.prototype points to null); the __proto__ property of objects created using function literals points to Function.prototype The object's __proto__ attribute points to Object.prototype).
In addition to the implicit property __proto__, the function object also has two implicit properties:
1. Function's context
2. The code that implements the function ’s behavior

Like object literals, we can use function literals to create functions. Similar to the following:

// Create a function using the literal method and assign it to the add variable
var add = function (a, b) {
    return a + b;
};
A function literal has four parts:
1. Function keyword, required.
2. Function name, optional. In the above example, the function name is omitted.
3. A series of parameters enclosed by parentheses, required.
4. A series of statements enclosed by curly braces, required. These statements will be executed when the function is executed.

Function call with this
When a function is called, in addition to the declared parameters, two additional parameters are implicitly passed: this and arguments.
This is very important in OOP, the value of this varies with the calling method. There are four calling methods in javascript:
1. method invocation pattern. When the function is called as a property of an object, this points to the object. This assignment process occurs when the function is called (that is, at runtime), which is called late binding
2. function invocation pattern. When the function is not called as an attribute, this refers to the global object. This is a design error. If it is correct, this within the internal function should refer to the external function. This problem can be solved by defining a variable in the function.

    var add = function (a, b) {return a + b;}
    var obj = {
        value: 3,
        double: function () {
            var self = this; // Assign this to self
            this.value = add (self.value, self.value);
        }
    }
    obj.double (); //obj.value is now 6
construct invocation pattern. Javascript is a prototype inheritance language, which means that objects can directly inherit properties from other objects without the concept of classes. This is not the same as inheritance in java. But javascript provides a syntax similar to java for creating objects. When a function is called with new, this points to the newly created object. The function at this time is usually called the constructor.
apply invocation pattern. When using the apply method of the function object to execute, this points to the first parameter of apply.
In addition to this, another parameter passed in when the function is called is arguments. It is a variable inside the function and contains all the parameters where the function is called, even the parameters that were not defined in the function.

var sum = function () {
    var i, sum = 0;
    for (i = 0; i <arguments.length; i + = 1) {
        sum + = arguments [i];
    }
    return sum;
};
sum (4, 8, 15, 16, 23, 42); // 108
It should be noted that the arguments here are not an array, it is just an array-like object with length property (Array-like), it does not have other methods of the array.
Regarding objects, let's finally talk about arrays. Arrays in JavaScript are not the same as arrays in normal programming.

Array object
An array is a data structure that is linearly allocated in memory, and the element offset is calculated by subscript, thereby extracting the element. The array should be a fast-access data structure, but in JavaScript, the array does not have this feature.
Array is an object with traditional array characteristics in javascript. This kind of object can convert the array subscript into a string, and then use this string as the key of the object, and finally take out the value corresponding to the key Explain that the object is a series of key-value pairs in javascript).

Although arrays in JavaScript are not as fast as arrays in traditional languages, because JavaScript is a weakly typed language, arrays in JavaScript can store any value. In addition, Array has many practical methods, you can go to MDN Array to view.
Javascript also provides a very convenient way to define the array (Array Literal):

var arr = [1,2,3]
The __proto__ of array objects created by array literals points to Array.prototype.

Inheritance
In Java, an object is an instance of a class, and one class can inherit from another class. But in javascript based on the prototype chain, objects can be created directly from another object.

When explaining the object above, we know that when creating an object, the object will automatically be assigned a __proto__ attribute. When using various types of literals (Literal), the javascript interpreter automatically assigns a value to __proto__. When we use the new operator to create an object in javascript, the javascript interpreter will also execute a statement similar to the following when constructing a function

     this .__ proto__ = {constructor: this};
The newly created object will have a __proto__ attribute, this attribute has a constructor attribute, and this attribute points to the new object. for example:

var d = new Date ()
d .__ proto __. constructor === Date // true here
If new is not an operator, but a function, its implementation is similar to the following code:

Function.prototype.new = function () {
    // Create a new object that inherits from the constructor ‘s prototype.
    var that = Object.create (this.prototype);
    // Invoke the constructor, binding –this- to the new object.
    var other = this.apply (that, arguments);
    // If its return value is n‘t an object, substitute the new object.
    return (typeof other === ‘object‘ && other) || that;
};
As mentioned earlier, the prototype-based inheritance mechanism is determined according to the semantics of the runtime, which provides us with great convenience. For example, if we want to add a map function to all Arrays, then we can do this:

Array.prototype.map = function (f) {
    var newArr = [];
    for (i = 0; i <this.length; i ++) {
        newArr.push (f (this [i]));
    }
    return newArr;
}
Because the __proto__ of all array objects points to the Array.prototype object, so we add a method to this object, then all array objects have this method.
The javascript interpreter will look at a method or property along the prototype chain. If you want to check whether an object has a certain property, you can use the Object.prototype.hasOwnProperty method.

to sum up
Through the above explanation many times, I hope you have a deeper understanding of the three concepts of objects in JavaScript, a series of key-value pairs, prototypes and functions. Use JavaScript to write front-end, back-end and script. At the React.js 2015 conference, Facebook announced React Native, which is about to be open source, which means that in the future we can use JavaScript to write IOS and Android native applications. I believe that with the release of ECMAScript 6, JavaScript language will have a series of earth-shaking changes, Stay Tuned. :-)

reference
JavaScript. The core
"Javascript: The Good Parts" strongly recommends everyone to read this book.


Object-oriented programming in javascript

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.