【问题标题】:multiple Element.prototype not working [duplicate]多个Element.prototype不起作用[重复]
【发布时间】: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


【解决方案1】:

我认为问题在于您将原型设置为新对象。 如果你使用 jQuery 或类似的东西,那么你可以这样做:

$.extend(Element.prototype, {
    hasClass : function(className){
        return this.className.contains(className, ' ');
    },
    getId: function(){
        return this.id;
    }
});

应该可以的。

【讨论】:

  • 我总是一次分配一个原型属性($.extend_.extend 都这样做)。我唯一一次直接分配给原型是在使用继承时:MyObj.prototype = new ParrentType();
  • 我不需要使用 jquery
  • @Sukima 你的意思是Child.prototype=Object.create(Parent.prototype) 不是吗? stackoverflow.com/questions/16063394/… 创建一个 Parent 的实例来设置为 Child 的原型是不好的,Parent 构造函数可能有一些初始化来创建在 Child.prototype 上没有业务的实例特定成员。
  • 是的,我的 ES3 天还没完。通常通过function Child() { Parent.call(this); }Child.prototype = new Parent() 管理。但是你是正确的 ES5 及以上Object.create 是更好的选择。我将开始研究在那里改变我的习惯。
猜你喜欢
  • 1970-01-01
  • 2014-08-16
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多