call与apply的作用与区别
1. 解析
在JavaScript
中Function
原型定义了两个方法,分别是Function.prototype.call
和Function.prototype.apply
。
每个函数都包含两个非继承而来的方法:call()
和apply()
;
在JavaScript
中,call
和apply
作用是一样的,都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部this的指向。
2. call()和apply()区别
两者的作用是一样的, 区别在于传入的参数不同
call():
第一个参数都是要传入给当前对象的对象,及函数内部的this; 从第二个参数开始往后,每个参数被依次传入函数。
apply():
第一个参数都是要传入给当前对象的对象,及函数内部的this; 第二个参数传递给函数的是参数数组。
function sum(x, y){
return this.a + this.b + x + y;
}
var obj = {a:1, b:2};
sum.call(obj, 3, 4); // 1 + 2 + 3 + 4 = 10
sum.apply(obj, [5, 10]); // 1 + 2 + 5 + 10 = 18
3. 具体实例
3.1 例子1
let obj = {
name: 'obj',
say: function(pre){
console.log((pre || 'none') + '--' + this.name)
}
}
let obj1 = {
name: 'obj1'
}
obj.say() // none--obj
obj.say.call(obj1,'call') // call--obj1
obj.say.apply(obj1,['apply']) // apply--obj1
3.2 例子2 复杂些的
function codeParam (item) {
item = item || {};
this.name = item.name || '';
this.type = item.type || 'string';
this.required = item.required;
this.description = item.description || '';
this.example = item.example || '';
}
function codeParamBase(item) {
codeParam.call(this,item);
this.in = 'path';
this.defaultValue = item.defaultValue || ''
}
let params = {
name: 'xxxx',
type: 'get',
required: true,
description: 'asdlkavasskldjf',
example: '这是一个哈哈',
in: '/path',
defaultValue: '300',
apiid: '2314901jkfsadf90q23kasdfk',
projectId: 2314124,
projectName: '项目京东'
}
let obj = new codeParamBase(params)
console.log(obj, obj.name, typeof obj);
console.log(params)
// 结果为:
{
name: 'xxxx',
type: 'get',
required: true,
description: 'asdlkavasskldjf',
example: '这是一个哈哈',
in: 'path',
defaultValue: '300' } 'xxxx' 'object'
{ name: 'xxxx',
type: 'get',
required: true,
description: 'asdlkavasskldjf',
example: '这是一个哈哈',
in: '/path',
defaultValue: '300',
apiid: '2314901jkfsadf90q23kasdfk',
projectId: 2314124,
projectName: '项目京东' }
4. 总结
obj.call(thisObj,arg1,arg2)
意思就是 obj的方法给到thisObj
或者说 thisObj 劫持 obj的方法
或者说 obj函数的的上下文,也就是obj函数体内部的this指向thisObj