JS 函数

函数: 由事件驱动的或者当它被调用时执行的可重复使用的代码块。

函数声明 函数表达式



//函数表达式
const speaking=function(){
    console.log('speaking');  
}


//函数调用
greeting();//调用
greeting();//调用
greeting();//调用

speaking();

//函数声明 
function greeting(){
    console.log('你好!')
}


//区别 声明提升  函数声明放在调用后方也可以执行  函数表达式必须放在前方

参数


//函数表达式
const greeting=function(name='默认',time='evening'){
    console.log(`hello,${name},${time}`);  
}

//函数调用
greeting('zt','morning');//调用
greeting('zttt','night');//调用

返回值

const calcArea =function(radius){
    let area=3.14*radius**2;
    return area
};

const area =calcArea(10);
console.log(area);

const calcVol=function (area){
   let volume=area*10;
   return volume;
}

const volume=calcVol(area);
console.log(volume);

箭头函数 =>

//常规函数

// const calcArea =function(radius){
//     let area=3.14*radius**2;
//     return area
// };

// const area =calcArea(10);
// console.log(area);


// //箭头函数
//一个参数优化
const calcAreas = radius => 3.14 * radius * 2;

const area = calcAreas(5);
console.log(area);

//箭头函数 2

// const greet=function(){
//      return 'hello world'
// }

const greet = () => 'hello world';
console.log(greet());


//箭头函数3

// const bill=function(products,tax){
//     let total=0;
//     for(let i=0;i<products.length;i++){
//         total += products[i]+products[i]*tax;
//     }
//     return total;
// }

const bill = (products, tax) => {

    let total = 0;
    for (let i = 0; i < products.length; i++) {
        total += products[i] + products[i] * tax;
    }
    return total
}



console.log(bill([5, 10, 15], 0.2));

箭头函数 和普通函数的区别

1,箭头函数使用箭头定义,普通函数中没有

2,箭头函数没有this ,箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply()  普通函数的this指向调用它的那个对象

3,箭头函数是匿名函数,不能作为构造函数,不能使用new

4,箭头函数不绑定arguments,取而代之需要用展开运算符解决...解决

5,箭头函数没有原型属性 prototype

 方法 和函数的区别

const names= 'henry';

//函数 functions
//常规函数调用 可以直接书写函数名称
const greet=()=>'Hello';

let resultOne=greet();
console.log(resultOne);

//方法 methods 与对象进行关联
//对象里面定义的函数称为方法 调用通过.调用
//对于函数来说可以在任何位置进行创建
let resultTwo=names.toUpperCase();
console.log(resultTwo);

回调函数和foreach

let person=['张毅','李四','赵武','无力'];

const logPerson=(person,index)=>{
    console.log(`${index}-${person}`)
}

person.forEach(logPerson);

回调函数:回调函数就是在一个函数执行完之后,要在它之后运行,被安排的明明白白的函数


function e(m,n,Callback){  
    var d = m+n;  
    alert("一个从父函数e 产生的参数将要被传递给回调函数 ,这个参数是:"+d);  
     
    //这里才写你想调用的函数---参数要正确  
    Callback(d);   
}  
function callback(data){  
        alert("我是回调函数,我的名字叫:callback ,我接收到来自父函数的参数,参数是:"+data);   
}
e(1,2,callback)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值