1, Reference A reference is a pointer to the actual location of the object. Look at the following example of using quotes:
]
In this example, two The objects all point to the same object. When the attribute content of one object is modified, it will affect the other.
Let’s look at another example. This time we use arrays to explain references:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
As shown in this example, When performing string operations, the result is always a new string object, not a modified version of the string. I don’t know if you have read the book "Advanced JavaScript Programming". There is a section about passing by value and passing by address. To put it bluntly, it is a reference. If you are interested, you can go and have a look.
JavaScript is a language that maintains a series of references to other objects. Through references, it can bring great flexibility to the program.
2. Function overloading
The characteristic of function overloading is to overload functions to exert different functions according to the different numbers or types of parameters passed in. It must rely on two things: one is to determine the number of incoming parameters, and the other is to determine the type of incoming parameters.
[Ctrl A Select all Note:
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
2-2,判断传入参数的类型
第一种判断类型的方式:
判断类型需要用到JavaScript中另一个操作符——typeof。 它用来表达变量内容的类型,返回的是字符串。比如如果一个变量是字符串,那么typeof后,则返回( "string" )。
经常我们会用到如下判断:
if( typeof num == "string" ){
num = parseInt( num );//如果是一个字符串,则把字符串解析出整数
}
if( typeof arr== "string" ){
arr= arr.split(",");//如果是一个字符串,则根据逗号来分割成数组
}
例如把前面的makeArr()函数改成只能接受字符串类型的参数,代码如下:
最终结果 a.length 为2,因为后面2个参数是number 类型。
第二种判断类型的方式:
此方法需要引用所有JavaScript对象都带有的一个属性,构造函数——constructor。这一属性引用的是原本用来构造该对象的那个函数。
if( num.constructor == String ){
num = parseInt( num );//如果是一个字符串,则把字符串解析出整数
}
if( arr.constructor == String ){
arr= arr.split(",");//如果是一个字符串,则根据逗号来分割成数组
}
if( newArr.constructor == Array ){
newArr = newArr.join(",");//如果是一个数组,则根据逗号来组成字符串
}
执行constructor后的结果是一个对象,而执行typeof后的结果是一个字符串。看下表的对比:
变量 |
typeof 变量 |
变量.constructor |
{a:"b"} |
"object" |
Object |
["a","b"] |
"object" |
Array |
function(){} |
"function" |
Function |
"a" |
"string" |
String |
66 |
"number" |
Number |
true |
"boolean" |
Boolean |
new User() |
"object" |
User |
通过对传入参数的数量和类型的判断,那么函数重载也就简单了。