Object type
The Object type is the most commonly used type in JavaScript. Although instances of Object don't have much functionality, they are ideal for storing and transferring data within an application.
There are two ways to create an Object instance. The first is to use the new operator followed by the Object constructor.
var person = new Object();
person .name = "tt";
person.age = 12;
Another way is to use object literal notation.
var person = {
name : 'tt' ,
age : 12
}
In addition, when using object literal syntax, if you leave its curly braces empty, you can define an object whose value contains default properties and methods.
var person = {}; //Same as new Object()
person.name = "tt";
person.age = 12;
Although you can use the previous Any of the methods introduced to define objects, but developers prefer the second method (object literal syntax) because this syntax requires less code and gives the feeling of encapsulating data. In fact, object literals are also the preferred way to pass a large number of optional parameters to functions, for example:
function showInfo(args)
{
if(args.name != undefined)
{
alert(args.name);
}
if(args.age != undefined)
{
alert(args.age);
}
}
showInfo({
name:'name',
age:12
});
showInfo({name:'name'});
Generally speaking, dots are used when accessing object properties. Notation, which is also a common syntax in many object-oriented languages. However, you can also use square bracket notation to access the properties of an object in JavaScript. For example:
alert(person.name);
alert(person['name']);
From a functional point of view, there is no difference between these two methods of accessing object properties. But the main advantage of square bracket syntax is that you can access properties through variables.
var propertyName = 'name';
alert( person[propertyName]);
In general, unless you must use variables to access properties, we recommend using dot notation.
Array type Arrays in JavaScript are quite different from arrays in most other languages. Although JavaScript arrays, like arrays in other languages, are ordered lists of data, unlike other languages, each item of a JavaScript array can hold any type of data. In other words, you can use the first position of the array to save the string, the second position to save the value, and the third position to save the object. Moreover, the size of the JavaScript array can be dynamically adjusted, that is, it can automatically grow as data is added to accommodate the new data.
There are two basic ways to create an array. The first is to use the Array constructor.
var colors1 = new Array();
var colors2 = new Array(20);
var colors3 = new Array('red','blue','yellow');
The second basic way to create an array is to use an array Literal representation.
var colors1 = [];
var colors2 = ['red','blue','yellow'];
When reading and setting array values, use square brackets and provide the 0-based numeric index of the corresponding value.
var colors = ['red','blue','yellow']; //Define a string array
alert(colors[0]); //Display the first item
colors[2] = 'green'; //Modify the third item
colors[3] = 'black'; //Add the fourth item
The length of the array is stored in its length property, this property will always return a value of 0 or greater.
var colors = ['red','blue', 'yellow'];
var names = [];
alert(colors.length); //3
alert(names.length); //0
Array The length property is very special - it is not read-only. Therefore, by setting this property, you can remove items from the end of the array or add new items to the array.
var colors = ['red','blue', 'yellow'];
colors.length = 2;
alert(colors[2]); //undefined
The array colors in this example initially has 3 values. Setting its length property to 2 will remove the last item, and as a result, accessing colors[2] will show undefined.
Using the length attribute, you can also easily add new items at the end of the array.
var colors = ['red','blue', 'yellow'];
colors[colors.length] = 'green'; //Add a color at position 3
colors[colors.length] = 'black'; //Add another color at position 4 Color
Since the index of the last item in the array is always length-1, the position of the next new item is length.
Conversion methods All objects have toLocaleString(), toString() and valueOf() methods. Among them, calling the toString() and valueOf() methods of the array will return the same value, that is, a comma-separated string formed by concatenating the strings of each value in the array. In fact, to create this string the toString() method of each item in the array is called.
var colors = ['red','blue', 'yellow'];
alert(colors.toString()); //red,blue,yellow
alert(colors.valueOf()); //red,blue,yellow
alert(colors) ; //red, blue, yellow
We first explicitly call the toString() and valueOf() methods to return the string representation of the array, and the string representation of each value is concatenated into A string separated by commas. The last line of code passes the array directly to alert(). Since alert() receives a string parameter, it will call the toString() method in the background, which will get the same result as calling the toString() method directly.
In addition, the toLocaleString() method often returns the same value as the toString() and valueOf() methods, but this is not always the case. When the toLocaleString() method of an array is called, it also creates a comma-delimited string of the array values. The only difference from the first two methods is that this time, in order to obtain the value of each item, the toLocaleString() method of each item is called instead of the toString() method. For example:
var person1 = {
toLocaleString: function (){
return "person1 : toLocaleString";
},
toString : function(){
return "person1 : toString";
}
};
var person2 = {
toLocaleString : function(){
return "person2 : toLocaleString";
},
toString : function(){
return "person2 : toString";
}
};
var people = [person1,person2];
alert(people); //person1 : toString,person2 : toString
alert(people.toString()); //person1 : toString,person2: toString
alert(people.toLocaleString()); //person1: toLocaleString,person2: toLocaleString
Array-inherited toLocaleString(), toString() and valueOf() methods , all return array items as comma-separated strings by default. And if you use the join() method, you can use different delimiters to build this string.
var colors = ['red','blue','yellow'];
alert(colors.join(',')); //red,blue,yellow
alert( colors.join('||')); //red||blue||yellow
Note: If the value of an item in the array is null or undefined, then the value is added in join The results returned by the (), toString(), toLocaleString() and valueOf() methods are represented by empty strings.
Stack methods
JavScript arrays also provide a way to make arrays behave like other data structures. Specifically, an array can behave like a stack, which is a data structure that can restrict the insertion and deletion of items. The stack is a last-in-first-out data structure. The insertion (called push) and removal (called pop) of items in the stack only occur in one location - the top of the stack. JavaScript provides push() and pop() methods to achieve similar stack behavior.
The push() method can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array. The pop() method removes the last item from the end of the array, reduces the length of the array, and returns the removed item.
var colors = new Array(); //Create a Array
var count = colors.push('red','blue'); //Push two items
alert(count); //2
count = colors.push('yellow') ; //Push another item
alert(count); //3
var item = colors.pop(); //Get the last item
alert(item); //yellow
alert(colors.length); //2
Queue method The access rule of the queue data structure is first in, first out. Queues add items to the end of the list and remove items from the front of the list. Since push() is a method that adds an item to the end of an array, all that is needed to simulate a queue is a method that gets an item from the front of the array. The array method that does this is shift(), which removes the first item in the array and returns it, decrementing the length of the array by one. Combining the shift() and push() methods, you can use arrays like queues:
var colors = new Array(); //Create an array
var count = colors.push('red','blue'); //Push two items
alert(count); //2
count = colors.push('yellow'); //Push another item
alert(count); //3
var item = colors.shift (); //Get the first item
alert(item); //red
alert(colors.length); //2
JavaScript also provides an unshift for arrays ()method. As the name suggests, unshift() does the opposite of shift(): it adds any number of items to the front of an array and returns the length of the new array. Therefore, using the unshift() and pop() methods simultaneously, you can simulate a queue in the opposite direction, that is, adding items to the front of the array and removing items from the end of the array, for example:
var colors = new Array(); //Create an array
var count = colors .unshift('red','blue'); //Push two items
alert(count); //2
count = colors.unshift('yellow'); //Push one more item
alert(count); //3
var item = colors.pop(); //Get the first item
alert(item); //blue
alert(colors.length); //2
Note: There is a deviation in IE's implementation of JavaScript. Its unshift() method always returns undefined instead of the new length of the array.
Reordering method There are already two methods that can be directly used to reorder the array: reverse() and sort(). The reverse() method will reverse Change the order of array items.
var values = [1,2,3,4, 5];
values.reverse();
alert(values); //5,4,3,2,1
By default, the sort() method is Sort the array items in ascending order - that is, the smallest value is at the front and the largest value is at the end. To implement sorting, the sort() method calls the toString() conversion method of each array item and then compares the resulting strings to determine how to sort. Even though each item in the array is a numeric value, the sort() method compares strings, as shown below:
var values = [0,1,5,10,15];
values.sort();
alert(values); //0,1 ,10,15,5
It can be seen that even if the order of the values in the example is correct, the sort() method will change the original order based on the result of the test string. Because although the value 5 is less than 10, when comparing strings, "10" is in front of "5". Therefore the sort() method can receive a comparison function as a parameter so that we can specify which value comes before which value.
function compare(value1,value2){
if(value1 < value2){
return 1;
} else if(value1 > value2){
return -1;
} else{
return 0;
}
}
var values = [0,1,5,10,15];
values.sort(compare);
alert(values); //15,10,5, 1,0
For numeric types or object types whose valueOf() method returns a numeric type, a simpler comparison function can be used. This function mainly subtracts the first value from the second value.
function compare(value1,value2){
return value2 - value1;
}
Operation methods JavaScript provides many methods for operating arrays. Among them, the concat() method can create a new array based on all the items in the current array. If one or more arrays are passed to the concat() method, the method will add each item in these arrays to the result. in the array. If the passed values are not an array, the values are simply added to the end of the resulting array.
var colors = ['red','green', 'blue'];
var colors2 = colors.concat('yellow',['black' , 'brown']);
alert(colors); //red,green,blue
alert( colors2); //red, green, blue, yellow, black, brown
The slice() method can create a new array based on one or more items in the current array. The slice() method can accept one or two parameters, which are the starting and ending positions of the item to be returned. With only one argument, the slice() method returns all items starting at the position specified by that argument and ending at the end of the current array. If given two arguments, this method returns the items before the start and end positions—but not including the items at the end position.
var colors = ['red',' green','blue','yellow','black','brown'];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(colors2); //green,blue,yellow,black,brown
alert(colors3); //green,blue,yellow
Let’s introduce splice( ) method, this method is probably the most powerful array method. The main purpose of splice() is to insert items into the middle of the array, but there are three ways to use this method.
Delete - You can delete any number of items by specifying 2 parameters: the position of the first item to be deleted and the number of items to be deleted. For example, splice(0,2) deletes the first two items in the array.
Insertion - You can insert any number of items into the specified position. You only need to provide 3 parameters: starting position, 0 (the number of items to be deleted), and the items to be inserted. If you want to insert multiple items, you can pass in the fourth and fifth items, or as many items as you want. For example, splice(2,0,'red','green') will insert the strings 'red' and 'green' starting from position 2 of the current array.
Replacement - You can insert any number of items into the specified position and delete any number of items at the same time. You only need to specify 3 parameters: the starting position, the number of items to be deleted and any number of items to be inserted. item. The number of items inserted does not have to equal the number of items deleted. For example, splice(2,1,'red','green') will delete the item at position 2 of the current array, and then insert the strings 'red' and 'green' starting from position 2.
var colors = ['red','green', 'blue'];
var removed = colors.splice(0,1); //Remove the first item
alert(colors); //green,blue
alert(removed); //red
removed = colors.splice(1,0,'yellow','black'); //Insert two items starting from position 1
alert(colors); //green,yellow,black,blue
alert(removed); //Return an empty array
removed = colors.splice(1,1,'red','brown'); //Insert two items and delete one item
alert(colors) ; //green,red,brown,black,blue
alert(removed); //yellow
Date type The Date type in JavaScript is built on the java.util.Date class in early Java. For this purpose, the Date type uses the number of milliseconds that have elapsed since 0:00 UTC January 1, 1970 to save the date. Under the conditions of using this data storage format, the date saved by the Date type can be accurate to 285,616 years before or after January 1, 1970.
To create a date object, use the new operator and the Date constructor.
var now = new Date();
When the Date constructor is called without passing parameters, the newly created object automatically gets the current date and time. If you want to create a date object based on a specific date and time, you must pass in the number of milliseconds that represent that date. To simplify this calculation process, JavaScript provides two methods: Date.parse() and Date.UTC().
Among them, the Date.parse() method receives a string parameter representing the date, and then attempts to return the milliseconds of the corresponding date based on this string. JavaScript does not define which formats Date.parse() should support, so the behavior of this method varies from implementation to implementation, and often from locale to locale. Browsers with the region set to the United States usually accept the following date formats:
● "month/day/year", such as: 6/13/2204
● "English month name day, Year", such as: January 12,2004
● "English day of the week, English month name, day, year, hour: minute: second time zone", such as: Tue May 25 2004 00:00:00 GMT-0700
For example, to create a date object for May 25, 2004, you can use the following code:
var someDate = new Date(Date.parse("May 25, 2004"));
If the string passed into the Date.parse() method cannot represent a date, then it will return NaN. In fact, if you pass a string representing a date directly to the Date constructor, Date.parse() will also be called behind the scenes. In other words, the following code is equivalent to the previous example:
var someDate = new Date('May 25, 2004');
The Date.UTC() method also returns the date represented of milliseconds, but it uses different information than Date.parse() when constructing the value. The parameters of Date.UTC() are the year and the 0-based month (January is 0, February is 1, and so on). The day of the month (1 to 31), the hour (0 to 23), minutes, seconds, and milliseconds. Of these parameters, only the first two (year and month) are required. If the number of days in the month is not provided, the number of days is assumed to be 1; if other parameters are omitted, they are assumed to be 0.
// GMT time at 0:00 on January 1, 2000
var y2k = new Date(Date.UTC(2000, 0));
//GMT time at 5:55:55 pm on May 5, 2005
var allFives = new Date(Date.UTC (2005,4,5,17,55,55));
Just like it imitates Date.parse(), the Date constructor also imitates Date.UTC(), but there is one obvious difference: both date and time are based on local time zone instead of GMT. The previous example can be rewritten as follows:
// Local time at 0:00 on January 1, 2000
var y2k = new Date(2000,0);
// Local time in 2005 May 5, 5:55:55 pm
var allFives = new Date(2005,4,5,17,55,55);
The Date type also has some methods specifically for formatting dates into strings. These methods are as follows:
● toDateString() - displays the day of the week, month and day in an implementation-specific format and year
● toTimeString() - Displays hours, minutes, seconds and time zone in implementation-specific format
● toLocaleDateString() - Displays day of the week, region-specific format Month, day and year
● toLocaleTimeString() - displays hours, minutes, seconds in an implementation-specific format
● toUTCString() - complete UTC in an implementation-specific format Date
The output of the above string formatting methods also varies from browser to browser, so no one method can be used to display consistent date information in the user interface.
The following are all methods of Date type:
Method |
Description |
Date() |
Returns the date and time of the current day. |
getDate() |
Returns the day of the month (1 ~ 31) from the Date object. |
getDay() |
Returns the day of the week (0 ~ 6) from a Date object. |
getMonth() |
Returns the month (0 ~ 11) from the Date object. |
getFullYear() |
Returns the year as a four-digit number from a Date object. |
getYear() |
Please use getFullYear() method instead. |
getHours() |
Returns the hour of the Date object (0 ~ 23). |
getMinutes() |
Returns the minute (0 ~ 59) of the Date object. |
getSeconds() |
Returns the number of seconds in a Date object (0 ~ 59). |
getMilliseconds() |
Returns the millisecond (0 ~ 999) of the Date object. |
getTime() |
Returns the number of milliseconds since January 1, 1970. |
getTimezoneOffset() |
Returns the difference in minutes between local time and Greenwich Mean Time (GMT). |
getUTCDate() |
Returns the day of the month (1 ~ 31) from a Date object based on universal time. |
getUTCDay() |
Returns the day of the week (0 ~ 6) from a Date object based on universal time. |
getUTCMonth() |
Returns the month (0 ~ 11) from the Date object according to universal time. |
getUTCFulYear() |
Returns the four-digit year from a Date object based on universal time. |
getUTCHours() |
Returns the hour of the Date object according to universal time (0 ~ 23). |
getUTCMinutes() |
Returns the minute of the Date object according to universal time (0 ~ 59). |
getUTCSeconds() |
Returns the seconds (0 ~ 59) of the Date object according to universal time. |
getUTCMilliseconds() |
Returns milliseconds (0 ~ 999) of a Date object according to universal time. |
parse() |
Returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string). |
setDate() |
Set the day of the month (1 ~ 31) in the Date object. |
setMonth() |
Set the month (0 ~ 11) in the Date object. |
setFullYear() |
Set the year (four digits) in the Date object. |
setYear() |
Please use the setFullYear() method instead. |
setHours() |
Set the hour (0 ~ 23) in the Date object. |
setMinutes() |
Set the minute (0 ~ 59) in the Date object. |
setSeconds() |
Sets the seconds in the Date object (0 ~ 59). |
setMilliseconds() |
Set the milliseconds (0 ~ 999) in the Date object. |
setTime() |
Sets the Date object in milliseconds. |
setUTCDate() |
Set the day of the month in the Date object (1 ~ 31) according to universal time. |
setUTCMonth() |
根据世界时设置 Date 对象中的月份 (0 ~ 11)。 |
setUTCFullYear() |
根据世界时设置 Date 对象中的年份(四位数字)。 |
setUTCHours() |
根据世界时设置 Date 对象中的小时 (0 ~ 23)。 |
setUTCMinutes() |
根据世界时设置 Date 对象中的分钟 (0 ~ 59)。 |
setUTCSeconds() |
根据世界时设置 Date 对象中的秒钟 (0 ~ 59)。 |
setUTCMilliseconds() |
根据世界时设置 Date 对象中的毫秒 (0 ~ 999)。 |
toSource() |
返回该对象的源代码。 |
toString() |
把 Date 对象转换为字符串。 |
toTimeString() |
把 Date 对象的时间部分转换为字符串。 |
toDateString() |
把 Date 对象的日期部分转换为字符串。 |
toGMTString() |
请使用 toUTCString() 方法代替。 |
toUTCString() |
根据世界时,把 Date 对象转换为字符串。 |
toLocaleString() |
根据本地时间格式,把 Date 对象转换为字符串。 |
toLocaleTimeString() |
根据本地时间格式,把 Date 对象的时间部分转换为字符串。 |
toLocaleDateString() |
根据本地时间格式,把 Date 对象的日期部分转换为字符串。 |
UTC() |
根据世界时返回 1970 年 1 月 1 日 到指定日期的毫秒数。 |
valueOf() |
返回 Date 对象的原始值。 |
Function type
What is the most interesting thing in JavaScript, I think it is the function - and the source of the fun is that the function is actually an object. Each function is an instance of the Function type and has the same properties and methods as other reference types. Since functions are objects, the function name is actually a pointer to the function object and will not be bound to a function.
Functions are usually defined using function declaration syntax, as shown in the following example:
function sum(num1,num2)
{
return num1 num2;
}
This is the same as the following function expression definition The methods are almost the same:
var sun = function(num1 ,num2){
return num1 num2;
};
The above code defines the variable sum and initializes it as a function. There is no function name after the function keyword. This is because when defining a function using a function expression, there is no need to use a function name - the function can be referenced through the variable sum. Also, note that there is a semicolon at the end of the function, just like when declaring other variables.
The last way to define a function is to use the Function constructor. The Function constructor can receive any number of parameters, but the last parameter is always regarded as the function body, while the previous parameters enumerate the parameters of the new function.
var sum = Function('num1','num2','return num1 num2'); //This method is not recommended
Since the function name is just a pointer to the function, the function name No different than any other variable containing a pointer to an object. In other words, a function may have multiple names, for example:
function sum(num1,num2)
{
return num1 num2;
}
alert(sum(10,10)); //20
var anotherSum = sum;
alert(anotherSum(10,10)); //20
sum = null;
alert(anotherSum(10,10)); //20
Note: Using a function name without parentheses accesses the function pointer, not calling the function.
Function declaration and function expression
So far, we have not distinguished between function declaration and function expression. In fact, when the parser loads data into the execution environment, it does not treat function declarations and function expressions equally. The parser will first read the function declaration and make it available (accessible) before executing any code; as for the function expression, it will not be actually interpreted and executed until the parser reaches the line of code where it is located.
alert(sum(10,10));
function sum(num1,num2)
{
return num1 num2;
}
The above code can run normally. Because before the code starts executing, the parser has already read the function declaration and added it to the execution environment. If you change the function declaration above to variable initialization as shown in the example below, it will cause an error during execution.
alert(sum(10,10));
var sum = function(num1,num2)
{
return num1 num2;
}
Function as value
Because the function name in JavaScript itself is a variable , so functions can also be used as values. That is, not only can you pass a function to another function like a parameter, but you can also return a function as the result of another function.
function callSomeFunction(someFunction, someArgument)
{
return someFunction(someArgument);
}
This function accepts two parameters, the first parameter should be a function, and the second parameter should be a value to be passed to the function. Then, you can pass the function like the following example:
function add(num)
{
return num 10;
}
var result = callSomeFunction(add,10);
alert(result); //20
Of course, it is possible to return a function from another function, and this is also an extremely useful technique.
function createSumFunction()
{
return function(num1,num2){
return num1 num2;
};
}
var sumFunction = createSumFunction();
alert(sumFunction(10,10)); / /20
Function internal attributes
Within a function, there are two special objects: arguments and this. Among them, arguments is an array-like object that contains all the parameters passed into the function, and the length attribute can be used to determine how many parameters are passed in.
function sayHi()
{
alert(arguments.length); //2
alert(arguments[0] ',' arguments[1]); //hello,world
}
sayHi('hello','world ');
Although the main purpose of arguments is to save function parameters, this object also has an attribute called callee, which is a pointer to the function that owns this arguments object. Look at the very classic factorial function below:
function factorial(num)
{
if(num <= 1){
return 1;
} else {
return num * factorial(num-1);
}
}
Defining the factorial function generally requires the use of a recursive algorithm; as in the above code, when the function has a name and the name will not change in the future, there is no problem in this definition. But the problem is that the execution of this function is tightly coupled with the function name factorial. In order to eliminate this tight coupling phenomenon, you can use arguments.callee as follows
function factorial(num)
{
if(num <= 1){
return 1;
} else {
return num * arguments.callee (num-1);
}
}
In the function body of this rewritten factorial() function, the function name factorial is no longer quoted. In this way, no matter what name is used when referring to the function, the recursive call can be guaranteed to complete normally. For example:
var trueFactory = factorial;
factorial = function(){
return 0;
};
alert(trueFactory(5)); //120
alert(factorial(5)); //0
Another special object inside the function is this. This refers to the function data to perform the operation - or it can also be said that this is the scope in which the function is executed (when in the global scope of the web page When a function is called in the scope, the this object refers to window). Look at the example below:
window.color = 'red';
var o = {color:'blue'};
function sayColor()
{
alert(this.color);
}
sayColor(); //red
o.sayColor = sayColor;
o.sayColor(); //blue
The above function sayColor() is defined in the global scope, and it refers to this object. Since the value of this is not determined before the function is called, this may refer to different objects during code execution. When sayColor() is called in the global scope, this refers to the global object window; in other words, evaluating this.color is converted to evaluating window.color, so the result is 'red'. When this function is assigned to object o and o.sayColor() is called, this refers to object o, so evaluating this.color will be converted into evaluating o.color, and the result is 'blue'.
Function properties and methods
Because functions in JavScript are objects, functions also have properties and methods. Each function contains two properties: length and prototype. Among them, the length attribute indicates the number of named parameters that the function hopes to receive.
function sayName(name)
{
alert(name);
}
function sayHi()
{
alert('hi');
}
alert(sayName.length); //1
alert(sayHi.length); //0
The most intriguing thing in JavaScript is the prototype attribute. For reference types, the prototype is the real place where all their instance methods are stored. Methods such as toString() and valueOf() are actually stored under the prototype name, but are accessed through instances of the respective objects. When creating custom reference types and implementing inheritance, the role of the prototype attribute is extremely important (the prototype attribute will not be introduced in detail here).
Each function contains two non-inherited methods: apply() and call(). The purpose of these two methods is to call a function in a specific scope, which is actually equivalent to setting the value of this object in the function body. First, the apply() method accepts two parameters: one is the scope in which the function is run, and the other is the parameter array. Among them, the second parameter can be an instance of Array or an arguments object. For example:
function sum(num1,num2)
{
return num1 num2;
}
function callSum1(num1,num2)
{
return sum.apply(this,arguments);
}
function callSum2(num1,num2)
{
return sum.apply(this,[num1,num2]);
}
alert(callSum1(10,10)); //20
alert(callSum2(10,10)); //20
In the above example, callSum1() passes this as the scope when executing the sum() function (because it works globally It is called in the domain, so the window object) and arguments object are passed in. And callSum2 also calls the sum() function, but it passes in this and a parameter array.
The call() method has the same function as the apply() method. The only difference between them is the way they receive parameters. For the call() method, the scope of the first parameter does not change. What changes is that the remaining parameters are passed directly to the function.
function callSum2(num1,num2)
{
return sum.call(this,num1,num2);
}
alert(callSum2(10,10)); //20
In fact, passing parameters is not apply This is where () and call() really come in; their real power is in their ability to extend the scope in which a function operates. Look at the example below:
window.color = 'red';
var o = {color:'blue'};
function sayColor()
{
alert(this.color);
}
sayColor(); //red
sayColor.call(this); //red
sayColor.call(window); //red
sayColor.call(o); //blue
In the above example, when sayColor.call(o) is run, the execution environment of the function is different, because the this object in the function body points to o, so the result displays "blue".
Note: Each function has a non-standard caller attribute, which points to the function that called the current function. Generally, within a function, tracing the call stack is implemented through arguments.callee.caller. Currently, IE, FireFox, and Chrome all support this attribute, but it is recommended to use this attribute for debugging purposes.
Built-in objects
There are two built-in objects in JavaScript: Global and Math.
Global object
The Global (global) object can be said to be the most special object in JavaScript, because no matter which angle you look at it, this object does not exist. The Global object in JavaScript is defined in a sense as the ultimate "catch-all object". In other words, properties and methods that do not belong to any other object are ultimately its properties and methods. In fact, there are no global variables or global functions; all properties and functions defined in the global scope are properties of the Global object. Such as isNaN(), parseInt() and parseFloat(), are actually all methods of the Global object, and the Global object also contains other methods.
URI encoding method
The encodeURI() and encodeURIComponent() methods of the Global object can encode the URI so that it can be sent to the browser. Certain characters, such as spaces, cannot be included in a valid URI. These two URI encoding methods can encode the URI. They replace all invalid characters with special UTF-8 encoding so that the browser can accept and understand it.
Among them, encodeURI() is mainly used for the entire URI (for example: http://www.test.com/test value.html), while encodeURIComponent() is mainly used for a certain segment of the URI (for example: http://www.test.com/test value.html) test value.html in the previous URI) is encoded. The main difference between them is that encodeURI() will not encode special characters that are part of a URI, such as colons, forward slashes, hellos, and pound signs; encodeURIComponent() will encode any non-standard characters it finds.
var uri = "http://www .test.com/test value.html#start";
//"http://www.test.com/test value.html#start"
alert(encodeURI(uri));
//"http://www.test.com/test value.html#start"
alert(encodeURIComponent(uri));
一般来说,使用encodeURIComponent()方法的时候要比使用encodeURI()更多,因为在实践中更常见的是对查询字符串参数而不是对基础URI进行编码。
与encodeURI()和encodeURIComponent()方法对应的两个方法分别是decodeURI()和decodeURIComponent()。其中,decodeURI()只能对encodeURI()替换的字符进行解码,同样,decodeURIComponent()只能对encodeURIComponent()替换的字符进行解码。
eval()方法
eval()方法大概是JavaScript中最强大的一个方法了,eval()方法就像是一个完整的JavaScript解析器,它只接受一个参数,即要执行的字符串。看下面的例子:
eval("alert('hi')");
这行代码的作用等价于下面这行代码:
alert('hi');
当解析器发现代码中调用eval()方法时,它会将传入的参数当做实际的JavaScript语句来解析,然后把执行结果插入到原位置。通过eval()执行的代码被认为是包含该次调用的执行环境的一部分,因此被执行的代码具有与该执行环境相同的作用域链。这意味着通过eval()执行的代码可以引用在包含环境中定义的变量,例如:
var msg = 'hello world';
eval('alert(msg)'); //hello world
可见,变量msg是在eval()调用的环境之外定义的,但其中调用的alert()仍然能够显示“hello world”。这是因为上面第二行代码最终被替换成了一行真正的代码。同样地,我们也可以在eval()调用中定义一个函数,然后再在该调用的外部代码中引用这个函数:
eval("function sayHi(){alert('hi')}");
sayHi();
注意:能够解释代码字符串的能力非常强大,但也非常危险。因此在使用eval()时必须极为谨慎,特别是在用它执行用户输入数据的情况下。否则,可能会有恶意用户输入威胁你的站点或应用程序安全的代码(即所谓的代码注入)。
Math对象
与我们在JavaScript直接编写的计算功能相比,Math对象提供的计算功能执行起来要快得多。Math对象还提供了辅助完成这些计算的属性。
属性 |
描述 |
E |
返回算术常量 e,即自然对数的底数(约等于2.718)。 |
LN2 |
返回 2 的自然对数(约等于0.693)。 |
LN10 |
返回 10 的自然对数(约等于2.302)。 |
LOG2E |
返回以 2 为底的 e 的对数(约等于 1.414)。 |
LOG10E |
返回以 10 为底的 e 的对数(约等于0.434)。 |
PI |
返回圆周率(约等于3.14159)。 |
SQRT1_2 |
返回返回 2 的平方根的倒数(约等于 0.707)。 |
SQRT2 |
返回 2 的平方根(约等于 1.414)。 |
The Math object contains the following methods:
方法 |
描述 |
abs(x) |
返回数的绝对值。 |
acos(x) |
返回数的反余弦值。 |
asin(x) |
返回数的反正弦值。 |
atan(x) |
以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。 |
atan2(y,x) |
返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。 |
ceil(x) |
对数进行上舍入。 |
cos(x) |
返回数的余弦。 |
exp(x) |
返回 e 的指数。 |
floor(x) |
对数进行下舍入。 |
log(x) |
返回数的自然对数(底为e)。 |
max(x,y) |
返回 x 和 y 中的最高值。 |
min(x,y) |
返回 x 和 y 中的最低值。 |
pow(x,y) |
返回 x 的 y 次幂。 |
random() |
返回 0 ~ 1 之间的随机数。 |
round(x) |
把数四舍五入为最接近的整数。 |
sin(x) |
返回数的正弦。 |
sqrt(x) |
返回数的平方根。 |
tan(x) |
返回角的正切。 |
toSource() |
返回该对象的源代码。 |
valueOf() |
返回 Math 对象的原始值。 |