简体   繁体   English

为什么apply 不能与classList 一起使用?

[英]Why can't apply be used with classList?

I'm trying to add to an element's classList in an environment where I don't have the spread syntax available.我试图在我没有可用的传播语法的环境中添加到元素的classList Using apply is failing with a TypeError:使用apply失败并出现 TypeError:

 const classes = 'red blue'; const tag = document.querySelector('#tag') const list = classes.split(/\\s/); console.log(list); // ['red', 'blue'] tag.classList.add.apply(tag, list); // Error tag.classList.add('green'); // doesn't happen
 .blue { background: blue } .red { color: red; } .green { border: 3px double green; }
 <p id="tag">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat nam nihil sed, dicta, maxime, atque nulla voluptatibus necessitatibus aliquam quasi inventore voluptas dolore labore ratione officia! Rerum vel, similique perferendis?</p>

Uncaught TypeError: Illegal invocation

I must be doing something incorrectly, because this works with spread.我一定是做错了什么,因为这适用于传播。 What's the problem with this invocation of classList.add ?调用classList.add有什么问题?

Docs for Function.apply() : Function.apply() 的文档:

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object). apply() 方法使用给定的this值调用函数,并以数组(或类似数组的对象)形式提供参数。

A natural question arises.一个自然的问题出现了。 What is this by default?什么是this默认? This is where your misunderstanding stems.这就是你的误解的根源。

Docs for this文档的

Take this snippet for instance.以这个片段为例。 It will create an object with a member method and put that object inside an outer object.它将使用成员方法创建一个对象并将该对象放入外部对象中。 What does it output?它输出什么?

 innerObj = { a: "inner", func: function() { return this.a; }, }; outerObj = { a: "outer", inner : innerObj }; console.log(outerObj.inner.func())

This shows that this by default will be the innermost object.这表明默认情况下this将是最里面的对象。 In your case, the code在你的情况下,代码

tag.classList.add('green');

will use the innermost object (aka classList ) as this .将使用最里面的对象(又名classList )作为this You applied the outer object tag as this and that's why you get a TypeError.您将外部对象tagthis ,这就是您得到 TypeError 的原因。

Hope this is clear希望这很清楚

You should use t instead of tag你应该使用t而不是tag

const classes = 'red blue';
const t = document.querySelector('#tag')
const list =  classes.split(/\s/);

t.classList.add.apply(t, list);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM