JS learning record (3) Function internals and regular expressions (2021-10-17)

1. Inside the function

1.1this and arguments

In ECMAScript 5, there are two special objects inside the function: arguments and this. ECMAScript
6 adds new.target attribute.

(For details, see JS Advanced Programming Fourth Edition p299-301)

The context object of the function: this
The object encapsulating the actual parameters: arguments

1.2 this-oriented

When is called in function form, this is always window.
When called as a method, this is the object on which the method is called.
When called as a constructor, this is the newly created object.
When calling with call and apply, this is the specified object passed in.

1.3 arguments

The arguments object is an array-like object that contains all the parameters passed in when calling the function.
This object only exists when the function is defined with the function keyword. Although it is mainly used to contain function parameters, the arguments object actually also has a callee attribute, which is a pointer to the function where the arguments object is located

//argument参数
function fun(a,b){
    
    
    //通过下标获取第一个参数
    console.log(arguments[0]);
    //通过下标获取第一个参数
    console.log(arguments[1]);
    //获取实参的个数
    console.log(arguments.length);
    //看看它的函数对象
    console.log(arguments.callee);
    console.log(arguments.callee == fun);    
}

fun("Hello","World");
/*
Hello
World
2
[Function: fun]
true
*/

2. Regular expressions

2.1 Analysis
//去除掉字符串中的前后的空格
var str = "  hello child  "
var reg = /^\s*|\s*$/g;
///^(在前)\s(空格)*(0或多个)|(或者)\s*$(在后)/g
console.log(str);
str = str.replace(reg, "");
console.log(str);
2.2 Note
// 检查手机号
var phoneStr = "15131494600";
var phoneReg = /^1[3-9][0-9]{9}$/;
console.log(phoneReg.test(phoneStr));
//若结尾无$,无法检查后面还有别的字符的情况
/*
var phoneReg = /^1[3-9][0-9]{9}/;
eg:15131494600www (true)
*/

3. Reference:

JavaScript and HTML DOM Reference Manual
Learn JavaScripts
JS Advanced Programming (4th Edition)

Guess you like

Origin blog.csdn.net/ariarko/article/details/120812247