主要用来处理函数内部的this指向问题
在(https://www.cnblogs.com/qimuz/p/12740831.html)中介绍了用构造函数来创建对象,其中里面的this指的是谁调用this,它就指向谁。
function animal() {}
animal.prototype = {
color: "grey",
look: function() {
console.log("It's color is " + this.color);
}
};
var dog = new animal();
dog.look(); // It's color is grey
var cat = new animal();
cat.look(); // It's color is grey
上图所示,打印出来的都是“It's color is grey”,但是如果我们想改变cat的颜色,就要重新定义一个look方法,如果改变的多了,就会很麻烦。
call()
call() 方法调用一个函数, 它具有一个指定的 this 值和分别地提供的参数
fun.call(thisArg, arg1, arg2, ...)
-
thisArg指的是在 fun 函数中指定的 this的值,是一个可选项
-
arg1, arg2, …指定的参数列表,也是可选项
-
使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
-
call()允许为不同的对象分配和调用属于一个对象的函数/方法
-
call()提供新的 this 值给当前调用的函数/方法。可以使用 call() 来实现继承:写一个方法,然后让另外一个新的对象来继承它,而不是在新对象中再写一次这个方法
比如前面的例子可以改为:
//使用 call() 方法调用函数并且指定上下文的 this function animal() {} animal.prototype = { color: "grey", look: function() { console.log("It's color is " + this.color); } }; var dog = new animal(); cat = { color:"white" }; dog.look.call(cat);
这样就更改了cat的颜色,输出为"It's color is white"
除此之外,还可以通过调用父构造函数的call()方法来实现继承
apply()
这个方法与call方法类似,区别就是call方法里面接受的是参数,而apply方法接受的是数组
fun.apply(thisArg, [argsArray]);
1、将数组添加到另一个数组
var arr = ["a", "b", "c"]; var nums = [1, 2, 3]; arr.push.apply(arr, nums); console.log(arr); //返回["a", "b", "c", 1, 2, 3]
结果为["a", "b", "c", 1, 2, 3]
concat()、push()、apply()的区别:
concat() 方法连接数组,不会改变原数组,而是创建一个新数组
push() 是接受可变数量的参数的方式来添加元素
apply() 则可以连接两个数组
2、apply() 方法及内置函数
var numbers = [3, 4, 6, 1, 9]; var max = Math.max.apply(null, numbers); console.log(max); //返回9
bind()
bind()方法创建一个新的函数(称为绑定函数),在调用时设置 this 关键字为提供的值。并在调用新函数时,将给定参数列表作为原函数的参数序列的前若干项。
fun.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg指的是当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用 new 操作符调用绑定函数时,该参数无效。参数:arg1,arg2,…表示当目标函数被调用时,预先添加到绑定函数的参数列表中的参数。
this.num = 6; var test = { num: 66, getNum: function() { return this.num; } }; test.getNum(); // 返回 66 var newTest = test.getNum; newTest(); // 返回 6 // 创建一个新函数,将"this"绑定到 test 对象 var bindgetNum = newTest.bind(test); bindgetNum(); // 返回 66