Home  >  Article  >  Web Front-end  >  JavaScript minimalist introductory tutorial (2): objects and functions_javascript skills

JavaScript minimalist introductory tutorial (2): objects and functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:32:55903browse

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

All other types are objects (let’s not be fooled by the return value of the typeof operator), for example:

1. Function
2.Array
3. Regular expression
4. Objects (objects are naturally objects)

Object Basics

In JavaScript, an object is a collection of attributes (an object is an associative array). Each attribute includes:

1. Attribute name, must be a string
2. Attribute value, which can be any value except undefined

Create an object from an object literal:

Copy code The code is as follows:

//Create an empty object through object literal {}
var empty_object = {};

Attribute name and attribute value of the object:

Copy code The code is as follows:

var stooge = {
// "first-name" is the attribute name, "Jerome" is the attribute value
"first-name": "Jerome",
// "last-name" is the attribute name, "Howard" is the attribute value
"last-name": "Howard"
};

If the attribute name is a legal identifier, the quotes can be omitted:

Copy code The code is as follows:

var flight = {
airline: "Oceanic",
Number: 815,
departure: {
IATA: "SYD",
Time: "2004-09-22 14:55",
City: "Sydney"
},
arrival: {
IATA: "LAX",
Time: "2004-09-23 10:42",
City: "Los Angeles"
}
};

Let’s look at an example of property access:

Copy code The code 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. A property that does not exist has a value of undefined. Objects are passed by reference rather than by value:

Copy code The code 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 properties of an object can be deleted using the delete operator:

Copy code The code 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 objects can inherit properties from the prototype object. We create an object through object literal, and its prototype object is Object.prototype object (Object.prototype object itself has no prototype object). When we create an object, we can set the prototype object of the object (we will discuss the specific setting method later). When trying to get (rather than modify) a property of an object, if the property does not exist on the object, JavaScript will try to get the property from the prototype object of the object. If the property does not exist in the prototype object, then from the prototype object The prototype object is searched, and so on, until the Object.prototype prototype object. Compared with getting attributes, when we modify a certain attribute of the object, it will not affect the prototype object.

Function Basics

In JavaScript, functions are also objects, which are linked to the Function.prototype prototype object (Function.prototype is linked to Object.prototype). The function has a property named prototype, and the type of its value is an object. This object has a property constructor, and the value of the constructor is this function:

Copy code The code 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 just like objects. That is to say, functions can be saved in variables or arrays, passed to functions as parameters, and functions can be defined inside functions. As a side note, functions have two hidden properties:

1. Function context
2. Function code

The function is created as follows:

Copy code The code 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 calls
2. Used by debuggers, development tools, etc. to identify functions

Many times we don’t need a function name. A function without a function name is called an anonymous function. The parameter list is enclosed in parentheses. JavaScript does not require actual parameters and formal parameters to match, for example:

Copy code The code is as follows:

var add = function(a, b) {
Return a b;
}

add(1, 2, 3); // Actual parameters and formal parameters do not match

If there are too many actual parameters, the extra actual parameters will be ignored. If there are too few actual parameters, the value of the unassigned formal parameter will be 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 beauty of JavaScript.

Function call

When each function is called, it will receive two additional parameters:

1.this
2.arguments

The value of this is related to the specific calling mode. There are four calling modes in JavaScript:

1. Method calling mode. If a property of an object is a function, it is called a method. If a method is called via o.m(args), this is the object o (it can be seen that this and o are only bound when the call is made), for example:

Copy code The code is as follows:

var obj = {
Value: 0,
increment: function(v) {
This.value = (typeof v === 'number' ? v : 1);
}
};
obj.increment(); // this === obj

2. Function calling mode. If a function is not a property of an object, then it will be called as a function, and this will be bound to the global object, for example:

Copy code The code is as follows:

message = 'Hello World';
var p = function() {
console.log(this.message);
}

p(); // Output 'Hello World'

This behavior is sometimes confusing. Let’s look at an example:

Copy code The code 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 the global object
        helper();
}
};

obj.increment(); // obj.value === 0

The desired result should be:

Copy code The code 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 calling mode. Functions intended to be prefixed with new are called constructors, for example:

Copy code The code is as follows:

// Test is called the constructor
var Test = function(string) {
This.message = string;
}

var myTest = new Test("Hello World");

A function can be called by adding new in front of it (such functions usually start with a capital). After adding new, an object linked to the prototype property of this function will be created, and this in the constructor will be this object.

4.apply calling 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 the parameter array, for example:

Copy code The code is as follows:

var add = function(a, b) {
Return a b;
}

var ret = add.apply(null, [3, 4]); // ret === 7

When the function is called, we can access a class array named arguments (not a real JavaScript array), which contains all the actual parameters, so that we can implement variable length parameters:

Copy code The code is as follows:

var add = function() {
var sum = 0;
for (var i=0; i         sum = arguments[i];
}
Return sum;
}

add(1, 2, 3, 4);

Exception

Now let’s talk about JavaScript’s exception handling mechanism. We use the throw statement to throw exceptions and the try-cache statement to catch and handle exceptions:

Copy code The code is as follows:

var add = function (a, b) {
If (typeof a !== 'number' || typeof b !== 'number') {
​​​​ // throw 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 for 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 string is String
5. The constructor of numbers is Number
6. The constructor of Boolean is Boolean
7. The constructor of regular expression is RegExp

We can add properties (often methods) to the prototype of the constructor to make this property available to related variables:

Copy code The code is as follows:

Number.prototype.integer = function() {
Return Math[this < 0 ? 'ceil' : 'floor'](this);
}

(1.1).integer(); // 1

Scope

JavaScript requires functions to build scope:

Copy code The code is as follows:

function() {
// ...
}();

An anonymous function is created and executed here. You can hide variables you don’t want to expose through scope:

Copy code The code is as follows:

var obj = function() {
//Hide value, inaccessible from outside
var value = 0;

Return {
// Only this method can modify 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 the prototype object associated with the object. We do this:

Copy code The code is as follows:

//Create an object o whose prototype object is {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:

Copy code The code is as follows:

// If 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 (compared to class-based inheritance, there is no need for the existence of a class, and the object directly inherits the object). Example:

Copy code The code 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 very simple, but it cannot protect private members. We can use module pattern. In the module pattern, a certain type of object is generated by a function, and the function scope is used to protect private members from external access:

Copy code The code is as follows:

// mammal function, used to construct mammal objects
var mammal = function(spec) {
// that is a constructed object
var that = {};

// Public method get_name can be accessed externally
That.get_name = function() {
// spec.name cannot be directly accessed from outside
         return spec.name;
};

// Public method says can be accessed externally
That.says = function() {
// spec.saying cannot be directly accessed from outside
          return spec.saying || '';
};

Return that;
};

//Create mammal object
var myMammal = mammal({name: 'Herb'});

//cat function, used to construct cat objects
var cat = function(spec) {
spec.saying = spec.saying || 'meow';

// cat inherits from mammal, so the mammal object is constructed first
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 the module pattern, inheritance is achieved by calling constructors. In addition, we can also access the methods of the parent class in the subclass:

Copy code The code 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_name 方法
    var that = cat(spec), super_get_name = that.superior('get_name');
    that.get_name = function(n) {
        return 'like ' super_get_name() ' baby';
    };
    return that;
};

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn