直接调用JS方法正常,但使用.call/.apply调用classList.remove方法报错
直接调用JS方法正常,但使用.call/.apply调用classList.remove方法报错
这个问题我之前也碰到过,核心原因是方法的上下文绑定出问题啦!
咱们先拆解下两种调用方式的区别:
- 正常调用
node.classList.remove('alert')的时候,remove方法的this是自动绑定到node.classList这个DOMTokenList实例上的,所以浏览器能正确识别并执行类名移除操作。 - 但当你把
remove方法单独取出来赋值给method时:let method = node['classList']['remove'];,这个方法就脱离了它原本的上下文。之后你用method.call(node, ['myclass']),相当于把this指定成了node这个DOM元素本身,而不是node.classList这个DOMTokenList对象,这就导致浏览器报错——你在一个不实现DOMTokenList接口的对象上调用了remove方法。
另外还有个小细节要注意:classList.remove()接受的参数是单个类名字符串(或者多个类名字符串),不是数组,你传['myclass']是不符合方法要求的哦。
下面给你几个正确的写法:
方法一:提前绑定正确的上下文
let method = node.classList.remove.bind(node.classList); method('myclass'); // 要移除多个类的话直接传多个参数 method('class1', 'class2');
方法二:调用时传入正确的this对象
let method = node.classList.remove; // 第一个参数传node.classList,而不是node method.call(node.classList, 'myclass'); // 移除多个类的写法 method.call(node.classList, 'class1', 'class2');
方法三:用apply传数组形式的多个类名
如果你的类名是存在数组里的,可以用apply来批量移除:
let classesToRemove = ['class1', 'class2']; let method = node.classList.remove; method.apply(node.classList, classesToRemove);
备注:内容来源于stack exchange,提问作者Cosoiu Constantin
相关产品推荐
相关产品推荐

