Javascript 为什么';不在DOM元素函数上应用工作?

Javascript 为什么';不在DOM元素函数上应用工作?,javascript,dom,Javascript,Dom,示例代码 document.body.getAttribute.apply(this,['id']); document.body.setAttribute.apply(this,['id','test']); 错误 火狐: TypeError:对未实现接口元素的对象调用了“setAttribute” 铬: 未捕获类型错误:非法调用 apply工作正常。它正在调用setAttribute函数,在该函数中this的值就是您设置它的值) 我们无法看到您正在将其设置为什么,因为您正在传递此,而没有向

示例代码

document.body.getAttribute.apply(this,['id']);
document.body.setAttribute.apply(this,['id','test']);
错误
火狐:

TypeError:对未实现接口元素的对象调用了“setAttribute”

铬:

未捕获类型错误:非法调用


apply
工作正常。它正在调用
setAttribute
函数,在该函数中
this
的值就是您设置它的值)

我们无法看到您正在将其设置为什么,因为您正在传递此,而没有向我们显示其值

显然,
这个
不是一个DOM元素,所以不能在它上面设置DOM属性

如果调用了
document.body.getAttribute()
,那么在
setAttribute
内部
this
的值将是
document.body
,它是一个DOM元素

在本例中,如果此是DOM元素,则可以看到它正在工作:

document.querySelector('div').setID=function(){
apply(这个,['id','test']);
}
document.querySelector('div').setID();
document.querySelector('div').innerHTML=document.querySelector('div').id
此功能:

document.body.setAttribute.apply(document.body,['id','test']);
document.body.getAttribute.apply(document.body,['id']);
在代码中(如果在任何函数之外执行),
引用窗口元素,因此您的代码相当于:

window.setAttribute("id","test");

这是不允许的

您需要应用
的具体原因是什么?由于
这是您的窗口对象。对其应用
id
可能不是很有用,甚至是不允许的。据我所知,我会采用这种方法:

document.body.getAttribute('id');
document.body.setAttribute('id','test');
document.body.getAttribute('id');

请随时纠正我:)

您从控制台.log(this)
中得到了什么,因为Firefox的错误消息清楚地表明,
this
不是一个元素。这就是原因。在我的代码中,我在Array.map函数中使用了apply,因此
这个
引用了新函数。谢谢,这是一个简单而完整的函数。正在努力获取这个简单的代码。