Simple JavaScript getting started tutorial (2): object and function _ javascript tips-js tutorial

Source: Internet
Author: User
Tags javascript array
This article mainly introduces the basic JavaScript tutorials (II): objects and functions. This article describes basic object knowledge, basic function knowledge, function calling, exceptions, inheritance, and so on, for more information about programming in other languages, see.

Simple types in JavaScript include:

1. Number
2. String
3. boolean (true and false)
4. null
5. undefined

Other types are objects (we should not be confused by the return values of the typeof operator), for example:

1. Functions
2. Array
3. Regular Expression
4. Objects (objects are also objects)

Object Basics

In JavaScript, an object is a set of attributes (the object is an associated array). Each attribute includes:

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

Create an object through the object literal:

The Code is as follows:


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

Object attribute name and attribute value:

The Code is as follows:


Var stooge = {
// "First-name" indicates the property name, and "Jerome" indicates the property value.
"First-name": "Jerome ",
// "Last-name" is the property name, and "Howard" is the property value
"Last-name": "Howard"
};

If the property name is a valid identifier, You can omit the quotation marks:

The Code is as follows:


Var flight = {
Airline: "Oceanic ",
Number: 815,
Departure :{
IATA: "SYD ",
Time ",
City: "sysydney"
},
Arrival :{
IATA: "LAX ",
Time ",
City: "Los Angeles"
}
};

Let's take a look at the example of attribute access:

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 property name is not a legal identifier, enclose it in quotation marks. The property value that does not exist is undefined. Objects are passed by reference rather than by value:

The Code is as follows:


Var x = {};
Var owner = x;
Owner. name = "Name5566 ";
X. name; // x. name = "Name5566"

Here, x and owner reference the same object.

You can use the delete operator to delete object attributes:

The Code is as follows:


Delete obj. x; // delete the x attribute of object obj

Prototype)

Each object is linked to a prototype object, which can inherit attributes from the prototype object. We create an Object through the Object literal. Its prototype Object is an Object. prototype Object (the Object. prototype Object itself has no prototype Object ). When creating an object, we can set the prototype object of the object (and then discuss the specific setting method ). When you try to obtain (rather than modify) an attribute of an object, if the object does not exist, JavaScript will try to obtain this attribute from the object's prototype object, if this attribute is not found in the prototype Object, search for it from the prototype Object of the prototype Object, and so on until the Object. prototype. When modifying an attribute of an object, the prototype object is not affected.

Function Basics

In JavaScript, a Function is also an Object. It is linked to the Function. prototype protoobject (Function. prototype is linked to Object. prototype ). A function has an attribute named prototype whose value type is an object. This object has a constructor. The value of constructor is the function:

The Code is as follows:


Var f = function (){}

Typeof f. prototype; // 'object'
Typeof f. prototype. constructor; // 'function'

F === f. prototype. constructor; // true

A function is an object. You can use a function just like an object. That is to say, a function can be saved in a variable or array and passed as a parameter to a function. A function can be defined inside the function. The function has two hidden attributes:

1. Context of the Function
2. Function Code

The function is created as follows:

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 function keyword is optional. The function name is mainly used for the following purposes:

1. For recursive calls
2. The function is identified by debuggers, development tools, and so on.

In many cases, we do not need a function name. A function without a function name is called an anonymous function. Enclosed in parentheses is the parameter list. JavaScript should not match realistic parameters and form parameters, for example:

The Code is as follows:


Var add = function (a, B ){
Return a + B;
}

Add (1, 2, 3); // The real parameter and the form parameter do not match

If there are too many arguments, the extra arguments will be ignored. If there are too few arguments, the value of the unassigned arguments will be undefined. The function must have a return value. If the return statement is not used to specify the return value, the return value of the function is undefined.

A function and its external variables constitute a closure. This is the key charm of JavaScript.

Function call

When a function is called, two additional parameters are received:

1. this
2. arguments

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

1. method call mode. If the object property is a function, it is called a method. If a method is called through o. m (args), this is the object o (it can be seen that this and o are bound only during the call). For example:

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 call mode. If a function is not an object property, it will be called as a function. At this time, this will be bound to a global object, for example:

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:

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 a global object.
Helper ();
}
};

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

The expected result is:

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 call mode. A function with the intention to use the new prefix is called a constructor. For example:

The Code is as follows:


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

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

Before a function, you can add new (such a function usually starts with an upper case). After adding new, an object linked to the prototype attribute of the function is created, and this is the object in the constructor.

4. apply call mode. The apply method of a function is used to call a function. It has two parameters: the first is this, and the second is the parameter array. For example:

The Code is as follows:


Var add = function (a, B ){
Return a + B;
}

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

When calling a function, we can access an array of classes named arguments (a non-real JavaScript array), which contains all the real parameters, so that we can implement the variable length parameter:

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 the Exception Handling Mechanism of JavaScript. We use the throw statement to throw an exception. The try-cache statement can capture and handle the exception:

The Code is as follows:


Var add = function (a, B ){
If (typeof! = 'Number' | typeof B! = 'Number '){
// Throw an exception
Throw {
Name: 'typeerror ',
Message: 'add needs numbers'
};
}
Return a + B;
}

// Capture and handle exceptions
Try {
Add ("seven ");
// E is the thrown exception object
} Catch (e ){
Console. log (e. name + ':' + e. message );
}

Add a property for the JavaScript type

Most types of JavaScript have constructors:

1. The Object constructor is an 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. Number Constructor
6. the Boolean constructor is Boolean.
7. The constructor of the regular expression is RegExp.

We can add an attribute to the prototype of the constructor (usually adding methods) to make this attribute available to relevant variables:

The Code is as follows:


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

(1.1). integer (); // 1

Scope

JavaScript uses functions to build scopes:

The Code is as follows:


Function (){
//...
}();

An anonymous function is created and executed here. Variables that do not want to be exposed can be hidden through the scope:

The Code is as follows:


Var obj = function (){
// Hide value, which 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;

Inheritance

There are many ways to inherit JavaScript implementations.
When creating an object, we can set the prototype object associated with the object. Let's do this:

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 the create method by yourself:

The Code 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 whose prototype is o
Return new F ();
};
}

Using the Object. create method, we perform prototype-based inheritance: a new Object directly inherits the attributes of an old Object (compared with class-based inheritance, there is no need for the existence of classes here, and the Object inherits objects directly ). Example:

The Code is as follows:


Var myMammal = {
Name: 'herb the mammal ',
Get_name: function (){
Return this. name;
},
Says: function (){
Return this. saying | '';
}
};

// Inherit from 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 the module mode. In module mode, an object is generated by a function and the function scope is used to protect private members from external access:

The Code is as follows:


// Mammal function, used to construct a mammal object
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 directly accessed from outside
Return spec. name;
};

// The public method says can be accessed externally
That. says = function (){
// Spec. saying external access failure
Return spec. saying | '';
};

Return that;
};

// Create a mammal object
Var myMammal = mammal ({name: 'herb '});

// Cat function, used to construct a cat object
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 the 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 a cat object
Var myCat = cat ({name: 'henrietta '});

In the module mode, inheritance is implemented by calling constructors. In addition, we can also access the methods of the parent class in the subclass:

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 ){
// Obtain 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;
};

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.