文章目录
笔者最近做js逆向碰到了call函数,上网查了半天也没查出个所以然,于是便做了实验验证。先说结论:
JS中只有函数或者方法有可以调用call函数,诸如a.call(b,arg1,arg2)本质上是b调用a方法,b可以是对象也可以是函数。所以上述可以视作a(arg1,arg2),其中参数是可选项。
a = {
add:function (a,b){
c = a + b;
return c;
}
}
b = {
sub:function(a,b){
c = a - b;
return c;
}
}
//b对象调用a对象中的add方法
res = a.add.call(b,1,2)
console.log(res)
//运行结果为3,可以视作a.add(1,2)
b对象调用a对象中的add方法,上述函数运行后结果为3
- 必须是函数或者方法才可以调用call函数
如下代码通过a对象直接调用call函数就会报错,报错提示为a.call不是一个函数(实际就是a不是一个函数),因为只有方法或者函数才能调用call函数
//JS代码
a = {
add:function (a,b){
c = a + b;
return c;
}
}
b = {
sub:function(a,b){
c = a - b;
return c;
}
}
//b对象调用a对象中的add方法
res = a.call(b,1,2)
console.log(res)
//运行结果
res = a.call(b,1,2)
^
TypeError: a.call is not a function
at Object.<anonymous> (C:\Users\Lucky\PycharmProjects\pythonProject\js逆向\今日头条\toutiao_JsCode.js:15:9)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.17.1
进程已结束,退出代码1
- 可以是一个对象调用另一个方法也可以是一个函数或者方法调用另一个方法
如下代码,通过b对象中的sub方法调用了a对象中的add方法
// JS代码
a = {
add:function (a,b){
c = a + b;
return c;
}
}
b = {
sub:function(a,b){
c = a - b;
return c;
}
}
//b对象的sub方法调用a对象中的add方法
res = a.add.call(b.sub,1,2)
console.log(res)
// 运行结果
3
进程已结束,退出代码0