三者是
Function
对象 原型上的三个方法,主要作用是改变函数中this
的指向。
Function.prototype.call()
- 用法:
function.call (thisArg, arg1, arg2, ...)
- 返回值:使用调用者提供的
this
值(也就是 thisArg)和参数 调用该函数的返回值,如果没有返回值,返回undefined
- 例子
// 简单例子 var a = { user: '测试', fn: function(a, b){ console.log(this.user); console.log(a, b); } } var b = a.fn.call(a, 1, 2); // this 指向 a , 返回 ‘测试 3’ // 稍复杂例子 function Product(name, price){ this.name = name; this.price = price; } function Food(name, price){ Product.call(this, name, price); // Producet 中的 this 指向当前 Food 的 this this.category = 'food'; } console.log(new Food('cheese', 5).name); // 返回 ‘cheese’ // 使用 call 方法调用匿名函数的例子 // 要求:为每一个数组元素对象添加一个 print 方法,这个 print 方法可以打印出各元素在数组中的正确索引 var animals = [ { name: 'king' }, { name: 'fail' } ] for(var i = 0; i < animals.length; i++){ (function(i){ this.print = function() { console.log('#' + i + '' + this.name); }; this.print() }).call(animals[i], i); // this 为 传入的每一个 animals 对象 } // 使用 call 调用函数,并且不传入第一个参数(即 thisArg) function display (){ var user = "测试"; console.log(this.user); } display.call(); // 在严格模式下,返回 undefined,非严格模式下,this 将会绑定全局对象,一版为 window
Function.prototype.apply()
-
用法:func.apply(thisArg, [argsArray])
-
返回值:调用有指定this值和参数的函数的结果。
-
备注:
call()
方法的作用和apply()
方法类似,区别就是call()
方法接受的是参数列表,而apply()
方法接受的是一个参数数组。 -
例子
// 用 apply 将数组各项添加到另一个数组 // 直接使用 push 方法会push一个完整的数组,concat方法又会返回一个新数组,下面这个方法很人性化,排除 [...array, ...elements] var array = ['a', 'b']; var elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] /* 找出数组中最大/小的数字 */ var numbers = [5, 6, 2, 3, 7]; var max = Math.max.apply(null, numbers); // 7
Function.prototype.bind()
-
用法:function.bind(thisArg[, arg1[, arg2[, …]]])
-
返回值:返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
-
备注:
bind()
方法创建一个新的函数,在bind()
被调用时,这个新函数的this
被指定为bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。 -
例子
const module = { x: 42, getX: function() { return this.x; } }; const unboundGetX = module.getX; console.log(unboundGetX()); // The function gets invoked at the global scope // expected output: undefined const boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // expected output: 42