call可借用原生方法,将目标对象作为this传入,如[].slice.call(nodelist)转类数组为数组;object.prototype.tostring.call精准判类型;string.prototype方法可安全操作非字符串值。

直接用 call 借用原生方法,关键在于把目标对象(比如类数组)作为第一个参数传进去,后面跟上原生方法原本接收的参数。
借用 Array.prototype 方法处理类数组
常见场景:DOM 节点列表(NodeList)、函数的 arguments、字符串等不是真数组但有长度和索引的对象。
-
转成数组:
Array.prototype.slice.call(nodeList)或更简洁的[].slice.call(nodeList) -
判断是否包含某值:
Array.prototype.includes.call('hello', 'e')→true -
查找索引:
Array.prototype.indexOf.call('world', 'o')→1
借用 Object.prototype 方法检测数据类型
比 typeof 更准确,尤其区分对象、数组、null 等:
-
Object.prototype.toString.call([])→"[object Array]" -
Object.prototype.toString.call(null)→"[object Null]" -
Object.prototype.toString.call(new Date())→"[object Date]"
借用 String.prototype 方法操作非字符串值
避免手动类型转换,直接调用字符串方法:
-
String.prototype.toUpperCase.call(123)→"123"(先转字符串再大写,数字无影响) -
String.prototype.trim.call(' hi ')→"hi"(即使传入已为字符串也安全) -
String.prototype.padStart.call(5, 3, '0')→"005"
注意 this 绑定和参数顺序
call 的第一个参数是方法内部的 this,后续参数逐个传入。别漏掉或错位:
- 错误写法:
Array.prototype.push.call(arr, item1, item2)✅ 正确(arr是this) - 错误写法:
Array.prototype.push.call(item1, arr, item2)❌this错了,会往item1上加元素(可能报错) - 想批量添加?用
push.apply(arr, [item1, item2])或现代写法arr.push(...[item1, item2])
不复杂但容易忽略:只要目标对象有对应属性结构(比如有 length 和数字索引),就能借 Array 方法;其他原生方法同理,关键是找准 this 指向和参数位置。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











