JS函数高级进阶,从三要素到五要素(含this)

JS函数三要素

一般认为,函数的三要素是:函数名,参数,函数体

JS函数进阶

想要深入的学习js,就要知道函数有五要素
函数名,参数,函数体,this,返回值

任何一个函数,在隐式原型上,都有四种很常见的方法,可以简单记忆为ABCC方法

apply,bind,call,constructor

如何在mdn中搜索到abc函数

在mdn中搜索,要搜索下面的关键词
Function.prototype.apply()
Function.prototype.bind()
Function.prototype.call()

函数原型中的ABC方法的语法

语法摘自MDN。
fn.apply(thisArg, [argsArray])
fn.bind(thisArg[, arg1[, arg2[, ...]]])
fn.call(thisArg, arg1, arg2, ...)

对ABC方法的理解,重中之重!!!!

最重要的两个问题。
1.谁是abc函数的发起者。
fn是abc函数的发起者。
他主动修改自己的this指向,并给自己传入参数。
所以,一切的都是fn在做事。跟其他人,没有一分钱的关系。
fn变异了自己的this,并传入了新的参数。
2.参数传到了哪里?谁运用了这些参数?
还是fn,fn使用了这些参数,运行了fn自己!!

函数原型ABC方法的用处

1.函数只写一次,复用,ES5继承,ES6继承
2.传入参数,得到结果
3.数组追加
    let arr1 = [12, 'foo', {name: 'fanchao'}, -1024];
    let arr2 = ['copyes', '22', 1024];
    Array.prototype.push.apply(arr1, arr2);
    console.log(arr1);
    // [ 12, 'foo', { name: 'fanchao' }, -1024, 'copyes', '22', 1024 ]
    Array.prototype.push.call(arr1, arr2);
    console.log(arr1);
    // [12, "foo", {…}, -1024, "copyes", "22", 1024, Array(3)]
4.求数组中的最大值和最小值
    let numbers = [5,665,32,773,77,3,996];
    let  max=Math.max(numbers)
    console.log(max)
    // 输出NaN

    let numbers = [5,665,32,773,77,3,996];
    let maxNum = Math.max.apply(Math, numbers);
    let maxNum2 = Math.min.call(Math, 5,665,32,773,77,3,996);

    console.log(maxNum);
    console.log(maxNum2);
    //为什么改变this指向,就能使用数组做参数了呢?
posted @ 2020-04-27 21:09  风意不止  阅读(595)  评论(0编辑  收藏  举报