Reading this article requires programming experience in other languages.
Simple types in JavaScript include:
1. Numbers
2. String
3. Boolean (true and false)
4.null
5.undefined
Other types are objects (we should not be confused by the return value of the typeof operator), for example:
1. Function
2.Array
3. Regular expressions
4. Object (Objects are naturally objects)
Object basis
In JavaScript, objects are collections of properties (the objects are associative arrays), each property includes:
1. The attribute name must be a string
2. The attribute value can be any value other than undefined
Create an object through object literal:
The code copy is as follows:
// Create an empty object through object literal {}
var empty_object = {};
The attribute name and attribute value of the object:
The code copy is as follows:
var stande = {
// "first-name" is the attribute name, and "Jerome" is the attribute value
"first-name": "Jerome",
// "last-name" is the attribute name, and "Howard" is the attribute value
"last-name": "Howard"
};
If the attribute name is a legal identifier, quotation marks can be omitted:
The code copy is as follows:
var flight = {
airline: "Oceanic",
number: 815,
department: {
IATA: "SYD",
time: "2004-09-22 14:55",
city: "Sydney"
},
arrival: {
IATA: "LAX",
time: "2004-09-23 10:42",
city: "Los Angeles"
}
};
Let's take a look at the example of property access:
The code copy is as follows:
var owner = { name: "Name5566" };
owner.name; // "Name5566"
owner["name"]; // "Name5566"
owner.job; // undefined
owner.job = "coder"; // Or owner["job"] = "coder";
If the attribute name is not a legal identifier, it needs to be wrapped in quotes. The value of the property that does not exist is undefined. Objects are passed by reference rather than by value:
The code copy is as follows:
var x = {};
var owner = x;
owner.name = "Name5566";
x.name; // x.name === "Name5566"
Here x and owner refer to the same object.
The attributes of an object can be deleted using the delete operator:
The code copy is as follows:
delete obj.x; // Delete the x attribute of object obj
Prototype of the object
Each object is linked to a prototype object, and the object can inherit attributes from the prototype object. We create an object through object literal, whose prototype object is an Object.prototype object (the Object.prototype object itself has no prototype object). When we create an object, we can set the object's prototype object (and then discuss the specific setting method). When trying to get (not modify) an attribute of an object, if the object does not exist, JavaScript tries to get the attribute from the prototype object of this object, if there is no such attribute in the prototype object, then look up from the prototype object of this prototype object, and so on until the Object.prototype prototype object. Compared to obtaining attributes, when we modify an object's attribute, it will not affect the prototype object.
Functional Basics
Functions are also objects in JavaScript, which are linked to the Function.prototype prototype object (Function.prototype links to Object.prototype). The function has a property named prototype, and its value is an object. This object has a property constructor, and the value of the constructor is this function:
The code copy is as follows:
var f = function() {}
typeof f.prototype; // 'object'
typeof f.prototype.constructor; // 'function'
f === f.prototype.constructor; // true
Functions are objects, you can use functions like using objects, that is, functions can be saved in variables and arrays, and can be passed as parameters to functions, and functions can be defined within functions. As a side note, the function has two hidden properties:
1. The context of the function
2. Function code
The function is created as follows:
The code copy is as follows:
var f = function add(a, b) {
return a + b;
}
console.log(f); // Output [Function: add]
The function name after the keyword function is optional. We formulate the function name mainly for several purposes:
1. For recursive call
2. Debuggers, development tools, etc. are used to identify functions
Many times we do not need function names, and functions without function names are called anonymous functions. A parameter list is wrapped in brackets. JavaScript does not require matching of real parameters and formal parameters, for example:
The code copy is as follows:
var add = function(a, b) {
return a + b;
}
add(1, 2, 3); // The actual parameter and the formal parameter do not match
If there are too many real parameters, then the excess real parameters will be ignored. If there are too few real parameters, then the value of the unassigned formal parameters is undefined. The function must have a return value. If the return value is not specified through the return statement, the function return value is undefined.
A function and the external variables it accesses form a closure. This is the key charm of JavaScript.
Function Calls
When each function is called, two additional parameters are received:
1.this
2.arguments
The value of this is related to the specific call pattern. There are four calling patterns in JavaScript:
1. Method calling mode. If an object's property is a function, it is called a method. If a method is called through om(args), this is an object o (which can be seen that this and o are bound only when called), for example:
The code copy is as follows:
var obj = {
value: 0,
increment: function(v) {
this.value += (typeof v === 'number' ? v : 1);
}
};
obj.increment(); // this === obj
2. Function call mode. If a function is not an object's property, it will be called as a function, and this is bound to the global object, for example:
The code copy is as follows:
message = 'Hello World';
var p = function() {
console.log(this.message);
}
p(); // Output 'Hello World'
This behavior is sometimes confusing, see an example:
The code copy is as follows:
obj = {
value: 0,
increment: function() {
var helper = function() {
// Add 1 to the value in the global object
this.value += 1;
}
// helper is called as a function
// Therefore this is a global object
helper();
}
};
obj.increment(); // obj.value === 0
The results we expect should be:
The code copy is as follows:
obj = {
value: 0,
increment: function() {
var that = this;
var helper = function() {
that.value += 1;
}
helper();
}
};
obj.increment(); // obj.value === 1
3. Constructor call mode. Functions that intend to use the new prefix are called constructors, for example:
The code copy is as follows:
// Test is called a constructor
var Test = function(string) {
this.message = string;
}
var myTest = new Test("Hello World");
A function can be called with new (such functions usually start with capitalization). After adding new, an object linked to the prototype property of this function will be created, and this object in the constructor is this object.
4. Apply call mode. The apply method of the function is used to call the function, which has two parameters, the first is this and the second is an array of parameters, for example:
The code copy is as follows:
var add = function(a, b) {
return a + b;
}
var ret = add.apply(null, [3, 4]); // ret === 7
When calling the function, we can access an array of classes called arguments (non-real JavaScript array) that contains all the arguments, so we can implement variable-length parameters:
The code copy is as follows:
var add = function() {
var sum = 0;
for (var i=0; i<arguments.length; ++i) {
sum += arguments[i];
}
return sum;
}
add(1, 2, 3, 4);
abnormal
Now let’s talk about the exception handling mechanism of JavaScript. We use the throw statement to throw exceptions, and the try-cache statement to catch and handle exceptions:
The code copy is as follows:
var add = function (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
// throw an exception
throw {
name: 'TypeError',
message: 'add needs numbers'
};
}
return a + b;
}
//Catch and handle exceptions
try {
add("seven");
// e is the thrown exception object
} catch (e) {
console.log(e.name + ': ' + e.message);
}
Add properties to JavaScript types
Constructors exist in most types in JavaScript:
1. The constructor of the object is Object
2. The constructor of the array is Array
3. The constructor of the function is Function
4. The constructor of the string is String
5. The constructor of the number is Number
6. The constructor of the boolean is Boolean
7. The constructor of the regular expression is RegExp
We can add properties (often add methods) to the constructor's prototype so that this property is available to related variables:
The code copy is as follows:
Number.prototype.integer = function() {
return Math[this < 0 ? 'ceil' : 'floor'](this);
}
(1.1).integer(); // 1
Scope
JavaScript needs to build scopes through functions:
The code copy is as follows:
function() {
// ...
}();
An anonymous function is created and executed here. Scope to hide variables that you do not want to be exposed:
The code copy is as follows:
var obj = function() {
// Hide value, cannot be accessed externally
var value = 0;
return {
// Only this method can modify the value
increment: function() {
value += 1;
},
// Only this method can read value
getValue: function() {
return value;
}
};
}();
obj.increment();
obj.getValue() === 1;
inherit
There are many ways to implement inheritance in JavaScript.
When creating an object, we can set up the prototype object associated with the object, and we do:
The code copy is as follows:
// Create an object o with its prototype object {x:1, y:2}
var o = Object.create({x:1, y:2});
The Object.create method is defined in ECMAScript 5. If you use ECMAScript 3, you can implement a create method yourself:
The code copy is as follows:
// If the Object.create method is not defined
if (typeof Object.create !== 'function') {
// Create Object.create method
Object.create = function (o) {
var F = function () {};
F.prototype = o;
// Create a new object, the prototype object of this object is o
return new F();
};
}
Through the Object.create method, we perform prototype-based inheritance: a new object directly inherits the properties of an old object (relative to class-based inheritance, there is no need for the existence of the class here, and the object directly inherits the object). example:
The code copy is as follows:
var myMammal = {
name: 'Herb the Mammal',
get_name: function() {
return this.name;
},
says: function() {
return this.saying || '';
}
};
// Inherit myMammal
var myCat = Object.create(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.purr = function(n) {
var i, s = '';
for (i = 0; i < n; i += 1) {
if (s) {
s += '-';
}
s += 'r';
}
return s;
};
myCat.get_name = function() {
return this.says() + ' ' + this.name + ' ' + this.says();
};
The above code is simple, but it cannot protect private members. We can use module mode. In module mode, a certain type of object is generated by a function and uses the function scope to protect private members from external access:
The code copy is as follows:
// mammal function, used to construct mammal objects
var mammal = function(spec) {
// that is the constructed object
var that = {};
// The public method get_name can be accessed externally
that.get_name = function() {
// spec.name cannot be accessed directly from outside
return spec.name;
};
// Public method says can be accessed externally
that.says = function() {
// spec.saying No direct access to external
return spec.saying || '';
};
return that;
};
// Create a mammal object
var myMammal = mammal({name: 'Herb'});
// cat function, used to construct cat object
var cat = function(spec) {
spec.saying = spec.saying || 'meow';
// cat inherits from mammal, so first construct the mammal object
var that = mammal(spec);
// Add public method purr
that.purr = function(n) {
var i, s = '';
for (i = 0; i < n; i += 1) {
if (s) {
s += '-';
}
s += 'r';
}
return s;
};
// Modify the public method get_name
that.get_name = function() {
return that.says() + ' ' + spec.name +
' ' + that.says();
return that;
};
};
// Create cat object
var myCat = cat({name: 'Henrietta'});
In module mode, inheritance is achieved by calling the constructor. In addition, we can also access the parent class's methods in the subclass:
The code copy is as follows:
Object.prototype.superior = function(name) {
var that = this, method = that[name];
return function() {
return method.apply(that, arguments);
};
};
var coolcat = function (spec) {
// Get the get_name method of the subclass
var that = cat(spec), super_get_name = that.superior('get_name');
that.get_name = function(n) {
return 'like ' + super_get_name() + ' baby';
};
return that;
};