程序员步步为营之JavaScript

JS-函数

2020-06-14  本文已影响0人  刘淘

1.函数基础 函数参数

函数写法:
function func(){}
var func=function(){}
经常使用对象来封装具有某一特定功能的函数集合,内部函数可简写为func(){}

var getName = function (name) {
    console.log(name)
}
getName('xiaoming')
const user = {
    name: null,
    getName() {
        return this.name
    },
    setName() {
        this.name = name
    }
}

函数参数

// 形参&实参
function sum(a, b) {
    console.log(a, b)
}
sum(1)        // 1, undefined
sum(1, 2, 3)  // 1, 2
// 默认参数
function avg(year = 1, total) {
    // year = year || 1
    return Math.round(total / year)
}
console.log(avg(3000))      // 3000
console.log(avg(3000, 2))   // 1500
function sort(arr, type = 'asc') {
    return arr.sort(function (a, b) {
        return type === 'asc' ? a - b : b - a
    })
}
console.log(sort([1, 3, 4, 2, 5]))
console.log(sort([1, 3, 4, 2, 5], 'desc'))

//利用扩展运算符计算arguments
function sum1() {
    return [...arguments].reduce((a, b) => a + b)
}
function sum2() {
    return Array.from(arguments).reduce((a, b) => a + b)
}
console.log(sum1(1, 1))
console.log(sum1(11, 11))
//使用扩展运算符声明参数,必须放到最后
function totalDisPrice(discount = 0, ...price) {
    return price.reduce((a, b) => a + b) * (1 - discount)
}
console.log(totalDisPrice(.1, 100, 200))



2.全局函数

//window自带的函数
console.log(window.screenX)
var screenX = function () {
    console.log('获取x轴的位置')
}
//覆盖window上已有成员,造成全局污染
console.log(window.screenX)
//放在一个对象上,避免覆盖window已有成员
const position = {
    screenX() {
        console.log('获取x轴的位置')
    },
}
console.log(position.screenX)

3.匿名函数

4.立即执行函数

(function(){
    console.log('somethig is wrong')
})()
//第三方库js:vendor.js
; (function (window) {
    'use strict'
    const getName = function () {
        console.log('from vendor:vendor Name')
    }
    window.vendor = { getName }
})(window)

//业务库 app.js
{
    const getName = function () {
        console.log('from app:app Name')
    }
    window.app = { getName }
}
//立即执行函数解决库之间的命名冲突问题
///在同一个页面引入vendor.js app.js
vendor.getName() //from vendor:vendor Name
app.getName() //from app:app Name


5.回调函数

 //<button name="callback">回调</button>
document.querySelector('[name="callback"]').addEventListener('click', function() {
      alert(this.innerHTML)
    })
    const nums = [1, 2, 3, 4, 5]
    // [10, 20, 30, 40, 50]
    console.log(nums.map(function(item) {
      item = item * 10
      return item
    }))

6.递归函数

// 阶乘
const factorial = function (num) {
    // if (num === 1) return 1
    // return num * factorial(num - 1)
    return num === 1 ? 1 : num * factorial(num - 1)
}
console.log(factorial(2))        // 120
// 求和
const sum = function (...args) {
    // if (!args.length) return 0
    // return args.pop() + sum(...args)
    return !args.length ? 0 : args.pop() + sum(...args)
}
console.log(sum(1, 2, 3, 4, 5))  // 15

7.箭头函数

const sum = function (...args) {
    return args.reduce(function (a, b) {
        return a + b
    })
}
//当箭头函数体只有一句话时,可去掉{}
const sum = (...args) => {
    return args.reduce((a, b) => {
        return a + b
    })
}
const sum = (...args) => args.reduce((a, b) => a + b)
console.log(sum(1, 2, 3, 4, 5))

8.this指针

//eg: <button name='landiao'>蓝调</button>
//eg: <button name='dianyin'>电音</button>
const music = {
    name: '音乐',
    show() {
        const landiao = document.querySelector('[name="landiao"]')
        const dianyin = document.querySelector('[name="dianyin"]')
        const _this = this
        landiao.addEventListener('click', function () {
            console.log(this) //<button name='landiao'>蓝调</button>
            console.log(`${_this.name}-${this.innerHtml}`)//音乐-蓝调
        })
        dianyin.addEventListener('click', (e) => {
            console.log(this) //{name:'音乐',show:f} 箭头函数的this就是定义时所在的对象
            console.log(`${this.name}-${e.target.innerHtml}`) //音乐-电音
        })
    },
    bind() {
        const buttons = document.querySelectorAll('button')
        buttons.forEach((item) => {
            console.log(this) //箭头函数的this就是其定义时所在的对象{name:'音乐',show:f,bind:f} 
            item.addEventListener('click', (e) => {
                console.log(this)  //箭头函数的this就是其定义时所在的对象{name:'音乐',show:f,bind:f}
                console.log(`${this.name}-${e.target.innerHTML}`)
            })
        })
    }
}
user.show()
user.bind()

9.call apply bind

//eg: <button name='landiao'>蓝调</button>
//eg: <button name='dianyin'>电音</button>
const user = {
    name: 'xiaoming',
}
function Person(url,skills){
    console.log(this.name,url,siklls)
}
Person.call(user,'http://baidu.com',['蓝调','电音'])
Person.apply(user,['http://baidu.com',['蓝调','电音']])
//bind bind bind start 
const fun1=Person.bind(user) //bind返回的是一个函数,不会立即执行
fun1('http://baidu.com',['蓝调','电音']) //bind的传参方式
const fun2=Person.bind(user,'http://baidu.com',['蓝调','电音'])
fun2() //执行bind返回的函数
//bind bind bind end

//应用1
function showInnerHtml(){
    alert(this.innerHtml())
}
const buttons=document.querySelectorAll('button')
buttons.forEach(item=>{
    item.addEventListener('click',(e)=>{
        show.call(e.target)
    })
})
//应用2 随机切换背景图
function Color(elem) {
    this.elem = elem
    this.colors = ['#9b59b6', '#1abc9c', '#34495e', '#e74c3c', '#f39c12']
    this.run = function () {
        setInterval(function () {
            //Math.floor向上取整 Math.random随机 (0~1)
            const index = Math.floor(Math.random() * this.colors.length)
            this.elem.style.backgroundColor = this.colors[index]
        }.bind(this), 1000)
    }
}
const color = new Color(document.body)
color.run()
function Request() {
    this.get = (params) => {
        const query = Object.keys(params).map(item => `${item}=${params[item]}`).join('&')
        const url = `http://baidu.com/${this.url}?${query}`
        console.log(url)
    }
}
// 继承
function Article() {
    this.url = 'article/list'
    Request.call(this)
    // Request.apply(this)
}
function User() {
    this.url = 'user/list'
    Request.call(this)
    // Request.apply(this)
}
const article = new Article()
const user = new User()
article.get({ id: '1', cat: 'js' })             // http://baidu.com/article/list?id=1&cat=js
user.get({ name: 'miracle', role: 'admin' })    // http://baidu.com/user/list?name=miracle&role=admin
上一篇 下一篇

猜你喜欢

热点阅读