【发布时间】:2014-10-22 21:19:09
【问题描述】:
Element.prototype = {
hasClass : function(className){
return this.className.contains(className, ' ');
},
getId: function(){
return this.id;
}
};
如果可行,请单独使用
String.prototype.contains = function(item, from){
return this.indexOf(item, from) != -1;
};
Element.prototype.hasClass = function(className){
return this.className.contains(className, ' ');
};
Element.prototype.getId = function() {
return this.id;
};
document.body.innerHTML=document.getElementById('foo').hasClass('blah');
<div id="foo" class="blah"></div>
这是我第一次和prototype打交道
【问题讨论】:
-
您正在覆盖原型,而不是扩展它。
-
离题了,但是你的
hasClass有点乱。contains的第二个参数作为第二个参数传递给.indexOf(),它需要一个索引号,而不是字符串。您传递的' '可能正在转换为0。你也会得到误报。...hasClass("la"); // true -
创建上述内容的最佳方法是什么?
-
您已经回答了这个问题:
individually if it works您正在将 Element 的整个原型替换为仅包含 2 个方法的对象。我不确定 JS 是否允许你替换 Element 的原型,这样方法就不会出现,或者它是否允许你破坏 Element。
标签: javascript prototype