我想重新实现jQuery函数。
例如.attr((.
我发现了一些这样的线索。
所以我尝试了一些类似的东西:
HTMLElement.prototype.attr = (pAttributeName, pAttributeValue) => {
if(pAttributeValue){
this.setAttribute(pAttributeName, pAttributeValue);
} else {
return this.getAttribute(pAttributeName);
}
};
但它不起作用。在构造函数中,我必须首先初始化元素吗
来自文档:
箭头函数表达式(也称为胖箭头函数(具有与函数表达式和词汇绑定相比,语法更短这个值
在您的情况下,this
绑定到window
对象。
使用正则函数
HTMLElement.prototype.attr = function(pAttributeName, pAttributeValue) {
if (pAttributeValue) {
this.setAttribute(pAttributeName, pAttributeValue);
} else {
return this.getAttribute(pAttributeName);
}
};
document.querySelector('h1').attr('id', 'head')
#head {
color: red;
}
<h1>Heading</h1>