【前端三剑客——JS】函数进阶(补充)

155 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第11天,点击查看活动详情

下面是对函数知识的一点补充,主要说明一个JS的三个内置函数

函数进阶

1. call apply bind

注意this的指向问题,谁调用this,它就指向谁

1.1 call

call()方法调用一个函数,其具有一个指定的this值和分别地提供的参数

fun.call(thisArg, arg1, arg2, ...)
  • thisArg指的是在fun函数中指定的this的值,如果指定了null或者undefined,则内部this指向window,同时值为原始值(数字,字符串.布尔值)的this会指向该原始值的自动包装,是一个可选项
  • arg1, arg2, …指定的参数列表。也是可选项。
  • 使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined
  • call() 允许为不同的对象分配和调用属于一个对象的函数/方法。
  • call() 提供新的 this 值给当前调用的函数/方法。你可以使用 call() 来实现继承:写一个方法,然后让另外一个新的对象来继承它(而不是在新对象中再写一次这个方法)

栗子

function foods() {}
foods.prototype = {
  price: "¥15",
  say: function () {
    console.log("My price is " + this.price);
  },
};
​
var apple = new foods();
orange = {
  price: "¥10",
};
apple.say.call(orange); // My price is ¥10
//this谁调用就指向谁

在子构造函数中,可以通过调用父构造函数的call()方法来实现继承

function Father(name, age){
    this.name = name;
    this.age = age;
}
function Son(name, age){
    Father.call(this, name, age);
    this.hobby = 'study';
}
var S = new Son('zhangsan', 18);
S;

apply()

与call相似,唯一区别是call方法接收的是参数,apply方法接收的是数组

fun.apply(thisArg,[argArray]);

栗子

var array = ['a', 'b', 'c'];
var nums = [1, 2, 3];
array.push.apply(array, nums);
array;

使用apply方法和内置函数

var numbers = [1,2,3,4,5,6];
var max = Math.max.apply(null, numbers);//apply作用接收数组
//直接使用max方法就是    Math.max(1,2,3,4,5,6);

bind

创建一个新的函数(称为绑定函数),调用时设置this关键字为提供的值,并在调用新函数时,将 给定参数列表作为原函数的参数序列的前若干项

fun.bind(thisArg[, arg1[,arg2[,...]]])

参数 thisArg:当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用 new 操作符调用绑定函数时,该参数无效。参数:arg1,arg2,…表示当目标函数被调用时,预先添加到绑定函数的参数列表中的参数

var bin = function () {
  console.log(this.x);
};
var foo = {
  x: 10,
};
​
bin(); // undefined
var func = bin.bind(foo); // 创建一个新函数把 'this' 绑定到 foo 对象
func(); // 10
this.num = 6;
var test = {
  num: 66,
  getNum: function () {
    return this.num;
  },
};
​
test.getNum(); // 返回 66
​
var newTest = test.getNum;
newTest(); // 返回 6, 在这种情况下,"this"指向全局作用域
​
// 创建一个新函数,将"this"绑定到 test 对象
var bindgetNum = newTest.bind(test);
bindgetNum(); // 返回 66

递归

function foo(n) {
  if (n == 0) {
    return 0;
  } // 临界条件
  else {
    return n + foo(n - 1);
  }
}
var a = foo(10);
a; // 55

闭包

是指函数可以使用函数之外定义的变量

简单闭包

var num = 3;
function foo() {
  console.log(num);
}
foo(); //打印 3

复杂闭包

Function对象

创建函数

var function_name = new Function(arg1, arg2, ... ,argN, function_body);

注意: 每个参数必须是字符串,function_body是函数主体,也就是要执行的代码

栗子

var add = new Function("a", "b", "console.log(a+b);");
add(2, 5); // 打印 7

函数属于引用类型,他们也有属性和方法,length声明函数期望的参数个数

Function 对象的方法

与所有对象共享的valueOf和toString

两个方法都返回函数的源代码