JavaScript方法call,apply,caller,callee,bind的使用详解及区别
JavaScript方法call,apply,caller,callee,bind的使用详解及区别
一、call 方法
调用一个对象的一个方法,以另一个对象替换当前对象(其实就是更改对象的内部指针,即改变对象的this指向的内容)。
即 “某个方法”当做“指定的某个对象”的“方法”被执行。
Js代码
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
参数
thisObj
可选项。将被用作当前对象的对象。
arg1, arg2, , argN
可选项。将被传递方法参数序列。
说明
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
举例一:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <style type="text/css"> </style> <script type="text/javascript"> function Obj() { this.value = "对象!"; } var value = "Global 变量"; function Fun1() { console.log(this.value); } window.Fun1(); Fun1.call(window); Fun1.call(document.getElementById('myText')); Fun1.call(new Obj()); </script> <title>Document</title> </head> <body> <input type="text" id="myText" value="input text"> </body> </html>
举例二:
var first_object = { num: 42 } var second_object = { num: 24 } function multiply(mult) { return this.num * mult; } console.log(multiply.call(first_object, 5)); console.log(multiply.call(second_object, 5));
二、apply方法
apply方法的第一个参数也是要传入给当前对象的对象,即函数内部的this。后面的参数都是传递给当前对象的参数。
对于apply和call两者在作用上是相同的,但两者在参数上有区别的。对于第一个参数意义都一样,但对第二个参数:apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入,而call则作为call的参数传入(从第二个参数开始),如 func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(func1, [var1,var2,var3])。同时,使用apply的好处是可以直接将当前函数的 arguments对象 作为apply的第二个参数传入。
var func = new function() { this.a = "func"; } var myfunc = function(x, y) { var a = "myfunc"; console.log(this.a); console.log(x+y); } myfunc.call(func, "var", "fun"); // "func" "varfun" myfunc.apply(func, ["var", "fun"]); // "func" "varfun"
三、caller 属性
返回一个对函数的引用,即调用了当前函数的函数体。
functionName.caller :functionName 对象是所执行函数的名称。
说明
对于函数来说,caller 属性只有在函数执行时才有定义。 如果函数是由 JScript 程序的顶层调用的,那么 caller 包含的就是 null 。如果在字符串上下文中使用 caller 属性,那么结果和 functionName.toString 一样,也就是说,显示的是函数的反编译文本。
function CallLevel() { if (CallLevel.caller == null) { console.log("CallLevel was called from the top level"); } else { console.log("CallLevel was called by another function:\n" + CallLevel.caller); } } function funCaller() { CallLevel(); } CallLevel(); funCaller();
四、callee属性
返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文。
[function.]arguments.callee:可选项 function 参数是当前正在执行的 Function 对象的名称。
说明
callee 属性的初始值就是正被执行的 Function 对象。
callee 属性是 arguments 对象的一个成员,它表示对函数对象本身的引用,这有利于匿 函数的递归或者保证函数的封装性,例如下边示例的递归计算1到n的自然数之和。而该属性仅当相关函数正在执行时才可用。还有需要注意的是callee拥有length属性,这个属性有时用于验证还是比较好的。arguments.length 是实参长度,arguments.callee.length 是形参长度,由此可以判断调用时形参长度是否和实参长度一致。
function callDemo() { console.log(arguments.callee); console.log(typeof arguments.callee); } function calleeLengthDemo(arg1, arg2) { if (arguments.length == arguments.callee.length) { console.log("验证形参和实参长度正确!"); return; } else { console.log("验证形参和实参长度不一致!"); console.log("实参长度: " + arguments.length); console.log("形参长度: " + arguments.callee.length); } } var sum = function(n) { if (n <= 0) { return 1; } else { return n + arguments.callee(n - 1); } } callDemo(); calleeLengthDemo(12); calleeLengthDemo(12, 96); calleeLengthDemo(12, 96, 45); console.log(sum(56));
五、bind
var first_object = { num: 42 } var second_object = { num: 24 } function multiply(mult) { return this.num * mult; } Function.prototype.bind = function(obj) { var method = this; temp = function() { return method.apply(obj, arguments); } return temp; } var first_multiply = multiply.bind(first_object); console.log(first_multiply(5)); // return 42 * 5 var second_multiply = multiply.bind(second_object); console.log(second_multiply(5)); // return 24 * 5
+++++++++++++++++++++++++++++++++++++++++++++++++++++
caller 与 callee 区别的一些举例:
function a() { b(); } function b() { console.log(b === arguments.callee); console.log(b.caller === a); console.log(arguments.callee.caller === a); } a();
//===============================
function calleeTest() { console.log(arguments.callee === calleeTest); console.log(arguments.callee.caller === calleeTest); console.log(arguments.callee.caller === arguments.callee); arguments.callee.say("Mr.Xu", " 您好"); // 获取当前函数句柄 } calleeTest.say = function(userName, value) { console.log(userName + "说: " + value); } function callerTest() { (function() { console.log(arguments.callee === callerTest); console.log(arguments.callee.caller === callerTest); console.log(arguments.callee.caller === arguments.callee); arguments.callee.caller.goodbye("Mr.Xu", "Mr.Wu"); // 获取调用当前函数的函数 })(); } callerTest.goodbye = function(userName, userName2) { console.log(userName + " 向 " + userName2 + " 说再见."); } calleeTest(); callerTest();
Javascript中bind()方法的使用与实现
superlin • April 03, 2015 • No Comments在讨论
bind()方法之前我们先来看一道题目:
var altwrite = document.write; altwrite("hello"); //1.以上代码有什么问题 //2.正确操作是怎样的 //3.bind()方法怎么实现
对于上面这道题目,答案并不是太难,主要考点就是this指向的问题,altwrite()函数改变this的指向global或window对象,导致执行时提示非法调用异常,正确的方案就是使用
bind()方法:
altwrite.bind(document)("hello")
当然也可以使用
call()方法:
altwrite.call(document, "hello")
本文的重点在于讨论第三个问题
bind()方法的实现,在开始讨论
bind()的实现之前,我们先来看看
bind()方法的使用:
绑定函数
bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值。常见的错误就像上面的例子一样,将方法从对象中拿出来,然后调用,并且希望this指向原来的对象。如果不做特殊处理,一般会丢失原来的对象。使用
bind()方法能够很漂亮的解决这个问题:
this.num = 9; var mymodule = { num: 81, getNum: function() { return this.num; } }; module.getNum(); // 81 var getNum = module.getNum; getNum(); // 9, 因为在这个例子中,"this"指向全局对象 // 创建一个'this'绑定到module的函数 var boundGetNum = getNum.bind(module); boundGetNum(); // 81
偏函数(Partial Functions)
Partial Functions也叫Partial Applications,这里截取一段关于偏函数的定义:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
这是一个很好的特性,使用
bind()我们设定函数的预定义参数,然后调用的时候传入其他参数即可:
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // 预定义参数37 var leadingThirtysevenList = list.bind(undefined, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
和setTimeout一起使用
一般情况下
setTimeout()的this指向window或global对象。当使用类的方法时需要this指向类实例,就可以使用
bind()将this绑定到回调函数来管理实例。
function Bloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1; } // 1秒后调用declare函数 Bloomer.prototype.bloom = function() { window.setTimeout(this.declare.bind(this), 1000); }; Bloomer.prototype.declare = function() { console.log('我有 ' + this.petalCount + ' 朵花瓣!'); };
注意:对于事件处理函数和setInterval方法也可以使用上面的方法
绑定函数作为构造函数
绑定函数也适用于使用new操作符来构造目标函数的实例。当使用绑定函数来构造实例,注意:this会被忽略,但是传入的参数仍然可用。
function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function() { return this.x + ',' + this.y; }; var p = new Point(1, 2); p.toString(); // '1,2' var emptyObj = {}; var YAxisPoint = Point.bind(emptyObj, 0/*x*/); // 实现中的例子不支持, // 原生bind支持: var YAxisPoint = Point.bind(null, 0/*x*/); var axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new Point(17, 42) instanceof YAxisPoint; // true
上面例子中Point和YAxisPoint共享原型,因此使用instanceof运算符判断时为true。
捷径
bind()也可以为需要特定this值的函数创造捷径。
例如要将一个类数组对象转换为真正的数组,可能的例子如下:
var slice = Array.prototype.slice; // ... slice.call(arguments);
如果使用
bind()的话,情况变得更简单:
var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); // ... slice(arguments);
实现
上面的几个小节可以看出
bind()有很多的使用场景,但是
bind()函数是在 ECMA-262 第五版才被加入;它可能无法在所有浏览器上运行。这就需要我们自己实现
bind()函数了。
首先我们可以通过给目标函数指定作用域来简单实现
bind()方法:
Function.prototype.bind = function(context){ self = this; //保存this,即调用bind方法的目标函数 return function(){ return self.apply(context,arguments); }; };
考虑到函数柯里化的情况,我们可以构建一个更加健壮的
bind():
Function.prototype.bind = function(context){ var args = Array.prototype.slice.call(arguments, 1), self = this; return function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return self.apply(context,finalArgs); }; };
这次的
bind()方法可以绑定对象,也支持在绑定的时候传参。
继续,Javascript的函数还可以作为构造函数,那么绑定后的函数用这种方式调用时,情况就比较微妙了,需要涉及到原型链的传递:
Function.prototype.bind = function(context){ var args = Array.prototype.slice(arguments, 1), F = function(){}, self = this, bound = function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return self.apply((this instanceof F ? this : context), finalArgs); }; F.prototype = self.prototype; bound.prototype = new F(); return bound; };
这是《JavaScript Web Application》一书中对
bind()的实现:通过设置一个中转构造函数F,使绑定后的函数与调用
bind()的函数处于同一原型链上,用new操作符调用绑定后的函数,返回的对象也能正常使用instanceof,因此这是最严谨的
bind()实现。
对于为了在浏览器中能支持
bind()函数,只需要对上述函数稍微修改即可:
Function.prototype.bind = function (oThis) { if (typeof this !== "function") { throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply( this instanceof fNOP && oThis ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments)) ); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; };来源: <http://blog.liuwanlin.info/javascriptzhong-bindfang-fa-de-shi-xian/>
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call、apply、caller、callee、bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript方法call,apply,caller,callee,bind的使用详解及区别
- JavaScript apply、call、caller、callee、bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析
- js apply/call/caller/callee/bind使用方法与区别分析