Introduction to JavaScript Minimalist tutorial (ii): _javascript Techniques for objects and functions

Source: Internet
Author: User

Reading this article requires programming experience in other languages.

The simple types in JavaScript include:

1. Digital
2. String
3. Boolean (True and False)
4.null
5.undefined

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

1. function
2. Array
3. Regular expressions
4. Objects (Objects naturally also objects)

Object base

In JavaScript, an object is a collection of attributes (objects are associative arrays), and each property includes:

1. Property name, must be a string
2. Property value, which can be any value other than undefined

To create an object from an object literal:

Copy Code code as follows:

To create an empty object through object literal {}
var empty_object = {};

Property name and attribute value of the object:

Copy Code code as follows:

var stooge = {
"First-name" is the property name, and "Jerome" is 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:

Copy Code code 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 attribute access:

Copy Code code 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 valid identifier, enclose it in quotation marks. A property value that does not exist is undefined. Objects are passed by reference rather than by value:

Copy Code code 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 code as follows:

Delete obj.x; Delete Object Obj's X property

The prototype of the object (prototype)

Each object is linked to a prototype object (prototype object), which inherits attributes from the prototype object. We create an object through object literal, its prototype object is Object.prototype object (Object.prototype object itself does not have a prototype object). When we create an object, we can set the object's prototype object (and then discuss the specific setup method). When you try to get (rather than modify) a property of an object, if the object does not exist, JavaScript attempts to get this property from the object's prototype object, and if it is not in the prototype object, look it up from the prototype object of the prototype object, and so on, until Object.prototype the prototype object. When we modify a property of an object, we do not affect the prototype object, compared to getting the property.

Function basics

In JavaScript, a function is also an object that is linked to a Function.prototype prototype object (Function.prototype link to object.prototype). The function has a property named prototype whose value is of type object, and this object has a property constructor,constructor value for this function:

Copy Code code 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 objects, that is, functions can be stored in variables, arrays, and can be passed as arguments to functions that can be defined inside functions. Incidentally, the function has two hidden properties:

1. The context of the function
2. The Code of the function

The function is created as follows:

Copy Code code 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, and we have developed a number of functions mainly for several purposes:

1. For recursive invocation
2. By the debugger, development tools, etc. used to identify functions

Many times we don't need a function name, and a function without a function name is called an anonymous function. There are parentheses wrapped in the list of parameters. JavaScript does not match realistic and formal parameters, for example:

Copy Code code as follows:

var add = function (A, b) {
return a + B;
}

Add (1, 2, 3); Arguments and formal parameters do not match

If there are too many arguments, the redundant actual attendees are ignored, and if the argument is too small, the value of the parameter that is not assigned is undefined. The function must have a return value, and the function return value is undefined if the return value is not specified through the returns statement.

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

Function call

When each function is invoked, two additional arguments are received:

1.this
2.arguments

The value of this is related to the pattern of the specific invocation, and there are four invocation modes in JavaScript:

1. Method invocation pattern. The property of an object is called a method if it is a function. If a method is invoked through O.M (args), this is Object O (this is why this and O are bound at the time of the call), for example:

Copy Code code 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 a property of an object, it will be invoked as a function, at which point this is bound to the global object, for example:

Copy Code code as follows:

message = "Hello World";
var p = function () {
Console.log (This.message);
}

P (); Output ' Hello world '

This kind of behavior sometimes makes people wonder, look at an example:

Copy Code code 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
So this is the global object
Helper ();
}
};

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

The results we expect should be:

Copy Code code 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 pattern. Functions that intend to use the new prefix are called constructors, for example:

Copy Code code 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 by adding new to it (such a function usually begins with a capitalization), plus new creates an object that links to the prototype property of this function, and this is the object in the constructor.

4.apply invocation mode. The Apply method of a function is used to invoke a function that has two arguments, the first is this, and the second is an array of arguments, for example:

Copy Code code as follows:

var add = function (A, b) {
return a + B;
}

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

Function call, we have access to an array of classes named arguments (not a true JavaScript array), which contains all the arguments, so that we can implement variable-length arguments:

Copy Code code 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 JavaScript's exception handling mechanism. We use the throw statement to throw the exception, try-cache the statement to catch and handle the exception:

Copy Code code 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;
}

Catching and handling exceptions
try {
Add ("seven");
E is the exception object thrown
catch (e) {
Console.log (e.name + ': ' + e.message);
}

Adding attributes for JavaScript types

Most types in JavaScript have constructors:

1. Object constructors are objects
2. The constructor of the array is array
3. Function constructor function
4. String constructor is string
5. Number of constructors
6. Boolean constructor is Boolean
7. The constructor of the regular expression is REGEXP

We can add attributes to the constructor's prototype (often add methods) so that this property is available to the related variables:

Copy Code code as follows:

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

(1.1). Integer (); 1

Scope

JavaScript requires functions to build scopes:

Copy Code code as follows:

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

An anonymous function was created and executed here. Scopes allow you to hide variables that you do not want to expose:

Copy Code code as follows:

var obj = function () {
Hidden 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;

Inherited

JavaScript implements inheritance in a number of ways.
When we create an object, we can set the prototype object associated with the object, and we do this:

Copy Code code as follows:

Creates 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, and if you use ECMAScript 3 You can implement a create method yourself:

Copy Code code 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;
Creates a new object that has a prototype object of O
return new F ();
};
}

Through the Object.create method we carry on prototype inheritance: A new object directly inherits the attributes of an old object (as opposed to class based inheritance, where the object is not required to be a class, and objects are inherited directly). Example:

Copy Code code 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 code above is simple, but it's impossible to protect private members. We can use module mode. In module mode, a class of objects is generated by a function and a function scope is used to protect private members from being accessed externally:

Copy Code code as follows:

Mammal function, used to construct mammal objects
var mammal = function (spec) {
That is the constructed object
var that = {};

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

Public method says can be accessed externally
That.says = function () {
Spec.saying external cannot be accessed directly
return Spec.saying | | '';
};

return to that;
};

Creating Mammal objects
var mymammal = mammal ({name: ' Herb '});

Cat function 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 Public method Purr
That.purr = function (n) {
var i, s = ';
for (i = 0; i < n; i + + 1) {
if (s) {
s + = '-';
}
s + = ' r ';
}
return s;
};

Modifying public methods Get_name
That.get_name = function () {
return that.says () + ' + Spec.name +
"+ that.says ();
return to that;
};
};

Creating a Cat Object
var Mycat = Cat ({name: ' Henrietta '});

In module mode, inheritance is accomplished by calling the constructor. In addition, we can access the method of the parent class in the child class:

Copy Code code 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 Get_name method of subclasses
var that = Cat (spec), Super_get_name = That.superior (' get_name ');
That.get_name = function (n) {
Return to ' like ' + super_get_name () + ' baby ';
};
return to that;
};

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.