JS 的 call apply bind 方法
js的call apply bind 方法都很常见,目的都是为了改变某个方法的执行环境(context)
call
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
thisObj
可选项。将被用作当前对象的对象。
arg1, arg2, argN ..
可选项。将被传递方法参数序列。
如果没设置严格模式 “use strict”
当thisObj 不存在或 为 undefined 或为 null 或为 this 时,则隐式地指向 全局对象(在浏览器中即为 window)
第二个参数是一个个值
apply
apply([thisObj[,arg1, arg2, argN]])
apply和call类似,区别只是第二个参数,是一个数组(或类数组)的形式
bind
bind(thisArg [, arg1 [, arg2, …]]);
bind 也是改变某个方法的执行环境,区别也在于第二个参数(也是一个个的参数形式)和“返回值”的特性。
它将一个func绑定给thisArg的上下文,并传入相应的参数,并以一个新函数的形式返回,以供调用。
如 func.call(func1,var1,var2,var3)
对应的apply写法为:func.apply(func1,[var1,var2,var3])
对应的bind写法为: func.bind(func1,var1,var2,var3)()
来举个栗子:
//'use strict' var name = 'name1';
var obj = {
name: 'name2',
sayName: function(str1,str2){
str1 = str1 || '';
str2 = str2 || '';
console.log(str1 + this.name + str2);
}
}; obj.sayName(); obj.sayName.bind(window,'Hello: ',' !')(); obj.sayName.apply(this,['hello: ',' ,']); obj.sayName.call(obj,'hello: ',' .');
将会输出:

注1:但IE9(包括IE9)以上的才支持bind
所以,在不支持bind的浏览器上,我们需要模拟一下
Function.prototype.Bind = function(context){
var self = this,
// 获取到bind第二个参数(中的所有参数)
args = Array.prototype.slice.call(arguments,1);
// 返回一个新的函数
return function(){
// 将相关参数赋给这个bind所在方法,并将执环境赋给context
return self.apply(context,args);
};
};
注2:
Function.prototype的apply和call是在1999年发布的ECMA262 Edition3中才加入的(1998年发布ECMA262 Edition2)。
在此前的的浏览器如IE5.01(JScript 5.0)中是没有apply和call的。因此也会带来一些兼容性问题。所以,
call的模拟:
Function.prototype.Call = function(context){
// 首先判断所给的context,即call的第一个参数
context = (context == undefined) ? window : context;
var temp = [],
evalStr = '';
// 最后要形成 一个eval字符串函数调用形式,以供动态执行
for(var i=1,j=arguments.length; i<j; i++){
temp.push('arguments[' + i + ']');
}
// 给context新增一个方法(拥有this值)
context._apply = this;
evalStr = 'context._apply(' + temp.join(',') + ')';
// console.log(evalStr);
try{
// 执行函数调用
eval(evalStr);
}catch(e){
throw new Error(e.message);
}finally{
// 销毁该属性
delete obj._apply;
}
};
apply的模拟:
apply也类似,因为第二个参数是类数组的形式,所以也要变换为数组
// 第二个参数 args是为了方便使用
Function.prototype.Apply = function(context,args){
context = (context == undefined) ? window : context;
var temp = [],
evalStr = '';
// 直接拿第二个参数数组的各个元素再进行组合join(',')
// 为什么不直接用 arguments[1]呢?
// 因为此时join也要用到 Array.prototype.join.call ,call又不一定支持
for(var i=0,j=args.length; i<j; i++){
temp.push('args[' + i + ']');
} context._apply = this;
evalStr = 'context._apply(' + temp.join(',') + ')';
// console.log(evalStr);
try{
eval(evalStr);
}catch(e){
throw new Error(e.message);
}finally{
delete obj._apply;
}
};
ok 来看一下对比效果
Function.prototype.Bind = function(context){
var self = this,
args = Array.prototype.slice.call(arguments,1);
return function(){
return self.apply(context,args);
};
};
Function.prototype.Call = function(context){
context = (context == undefined) ? window : context;
var temp = [],
evalStr = '';
for(var i=1,j=arguments.length; i<j; i++){
temp.push('arguments[' + i + ']');
}
context._apply = this;
evalStr = 'context._apply(' + temp.join(',') + ')';
console.log(evalStr);
try{
eval(evalStr);
}catch(e){
throw new Error(e.message);
}finally{
delete obj._apply;
}
};
Function.prototype.Apply = function(context,args){
context = (context == undefined) ? window : context;
var temp = [],
evalStr = '';
for(var i=0,j=args.length; i<j; i++){
temp.push('args[' + i + ']');
}
context._apply = this;
evalStr = 'context._apply(' + temp.join(',') + ')';
console.log(evalStr);
try{
eval(evalStr);
}catch(e){
throw new Error(e.message);
}finally{
delete obj._apply;
}
};
var name = 'name1';
var obj = {
name: 'name2',
sayName: function(str1,str2){
str1 = str1 || '';
str2 = str2 || '';
console.log(str1 + this.name + str2);
}
};
obj.sayName();
obj.sayName.bind(window,'Hello: ',' !')();
obj.sayName.Bind(window,'Hello: ',' !')();
obj.sayName.apply(this,['hello: ',' ,']);
obj.sayName.Apply(this,['hello: ',' ,']);
obj.sayName.call(obj,'hello: ',' .');
obj.sayName.Call(obj,'hello: ',' .');

JS 的 call apply bind 方法的更多相关文章
- JS中call,apply,bind方法的总结
why?call,apply,bind干什么的?为什么要学这个? 一般用来指定this的环境,在没有学之前,通常会有这些问题. var a = { user: "小马扎", fn: ...
- JavaScript中call,apply,bind方法的区别
call,apply,bind方法一般用来指定this的环境. var a = { user:"hahaha", fn:function(){ console.log(this.u ...
- JavaScript内置一些方法的实现原理--new关键字,call/apply/bind方法--前戏
new关键字,call/apply/bind方法都和this的绑定有关,在学习之前,首先要理解this. 一起来学习一下this吧 首先.this是一个对象. 对象很好理解,引用类型值,可以实现如th ...
- JavaScript中call,apply,bind方法的总结。
why?call,apply,bind干什么的?为什么要学这个? 一般用来指定this的环境,在没有学之前,通常会有这些问题. var a = { user:"追梦子", fn:f ...
- js: this,call,apply,bind 总结
对js中的一些基本的很重要的概念做一些总结,对进一步学习js很重. 一.this JavaScript 中的 this 总是指向一个对象,而具体指向那个对象是在运行时基于函数的执行环境动态绑定的,而非 ...
- call,apply,bind方法的总结
why?call,apply,bind干什么的?为什么要学这个? 一般用来指定this的环境,在没有学之前,通常会有这些问题. var a = { user:"追梦子", fn:f ...
- JavaScript中call,apply,bind方法的总结
原文链接:http://www.cnblogs.com/pssp/p/5215621.html why?call,apply,bind干什么的?为什么要学这个? 一般用来指定this的环境,在没有学之 ...
- JavaScript中call,apply,bind方法
why?call,apply,bind干什么的?为什么要学这个? 一般用来指定this的环境,在没有学之前,通常会有这些问题. var a = { user:"追梦子", fn:f ...
- prototype.js中Function.prototype.bind方法浅解
prototype.js中的Function.prototype.bind方法: Function.prototype.bind = function() { var __method = this; ...
随机推荐
- android studio clone 失败
Clone failedunable to access 'https://git.oschina.net/xx/xx.git/': Failed to connect to x.tu26.net p ...
- 九宫格抽奖HTML+JS版
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- python查找算法的实现-二分法
1.算法:(设查找的数组期间为array[low, high]) (1)确定该期间的中间位置K(2)将查找的值T与array[k]比较.若相等,查找成功返回此位置:否则确定新的查找区域,继续二分查找. ...
- C语言程序代写
MTRX1702 - C ProgrammingAssignment 1This assignment requires you to design and build a program to co ...
- eclipse 运行报java.lang.OutOfMemoryError: PermGen space解决方法
一.在window下eclipse里面Server挂的是tomcat6,一开始还是以为,tomcat配置的问题,后面发现,配置了tomcat里面的catalina.bat文件,加入 set JAVA_ ...
- PL-SQL 存储函数和存储过程
PL-SQL 存储函数和存储过程 ORACLE 提供能够把PL/SQL 程序存储在数据库中,并能够在不论什么地方来执行它.这样就叫存储过程或函数. 过程和函数统称为PL/SQL子程序.他们是被命 ...
- [AX2012]Claims user
AX2012可以创建一种account type为claims user的账号,这种账号不需要在AD中事先已创建用户,但是claims账号是无法通过rich client登陆到AX,它的主要应用场景是 ...
- LoadRunner执行过程报错“Failed to connect to server "xxx.xxx.xxx.xxx:xx":[10060] connetion time out”
执行性能测试过程中,LR报错: Action.c(6):Error -27796: Failed to connect to server "xxx.xxx.xxx.xxx:xx" ...
- GitHub 操作流程示例
最新文章:Virson's Blog 参考文章: 博客园-Web前端开发,博客园-喻头快跑,GotGitHub 首先.通过github网站新建一个仓库,得到仓库地址 https://github.co ...
- [PaPaPa][需求说明书][V2.0]
前 言 大家好,我是“今晚打老虎”. 什么? 你问我为什么这次亮字号了? 还不是因为哥太出名了,即使我不亮你们也知道是我写的了. 自从发布了V1.0版本之后.群里又进来好多人.30K大大分发的任务 ...