Javascript 函数
函数的声明
- js中的函数是Function类创建的实例
let zy=new Function("a","console.log(a)");
zy("我爱你"); //我爱你
- 使用函数声明定义函数
function test(){
return ("test functions");
}
console.log(test());
- 对象字面量属性
let test={
name:null,
getName:function(){
return this.name;
},
// 简写模式
setName(value){
this.name=value;
}
}
test.setName("zyzy");
console.log(test.getName()); //zyzy
- 全局函数会声明在window对象中。当定义screenY函数后就会覆盖window.screenY方法
console.log(window.screenY);// 56
function screenY(){
return ("screenY is changed");
}
console.log(window.screenY());//screenY is changed
使用 let/const 时不会压入window
let zy =function(){
console.log("zy");
}
window.zy();//window.zy is not a function
// var声明的变量会往window压
var zy1 =function(){
console.log("zy1");
}
window.zy1(); //zy1
匿名函数
- 函数是对象,所以可以通过赋值来指向到函数对象的指针,当然指针也可以传递给其他变量
let test=function(num){
return(++num);
};
console.log(test instanceof Object); //true
- 标准声明的函数优先级更高,解析器会优先提取函数并放在代码树顶端,所以标准声明函数位置不限制,所以下面的代码可以正常执行。
console.log(test1(3));
function test1(num) {
return ++num;
- 赋值声明时则报错,匿名函数不会提升
console.log(test1(3)); // Cannot access 'test1' before initialization
let test1=function(num) {
return ++num;
};
立即执行函数
-可以用来定义私有作用域防止污染全局作用域
(function test(){
var web="this is web";
})();
console.log(web);//web is not defined
- 使用 let/const 有块作用域特性,所以使用以下方式也可以产生私有作用域
{
let web="web";
}
console.log(web);//web is not defined
var 没有块作用域特性
{
var web="web";
}
console.log(web);//web
形参实参
- 形参数量大于实参时,没有传参的形参值为 undefined
- 实参数量大于形参时,多于的实参将忽略并不会报错
默认参数
下面通过排序来体验新版默认参数的处理方式,下例中当不传递 type 参数时使用默认值 asc。
// 采用默认参数数组排序
function sortArray(arr,type='asc'){
return arr.sort((a,b)=>type=='asc'?a-b:b-a);
}
console.log(sortArray([1,3,2,7,4],'dasc'));//(5) [7, 4, 3, 2, 1]
// sort排序原理
function sort(array,callback){
for(const n in array){
for (const m in array) {
if(callback(array[n],array[m])<0){
const temp =array[n];
array[n]=array[m];
array[m]=temp;
}
}
}
return array;
}
arr =sort([4,1,3,9,5],function(a,b){
return b-a;
});
console.log(arr);//(5) [9, 5, 4, 3, 1]
- 默认参数要放在最后面
函数参数
利用arguments求和
方法一:
function sum(){
// console.log(arguments);
let total=0;
for(let i=0;i<arguments.length;i++){
total+=arguments[i];
}
return total;
}
console.log(sum(1,2,3,4,5));
方法二
function sum(){
//由于arguments是为数组,所以用点函数转换成数组
return [...arguments].reduce((a,b)=>a+b);
}
console.log(sum(1,2,3,4,5));
方法三
function sum(...args){
// onsole.log(args);c
return args.reduce((a,b)=>a+b);
}
console.log(sum(1,2,3,4,5));