如何添加原型方法

时间:2014-03-12 22:59:47

标签: javascript oop prototype

所以这是我班级的一部分

this.$e = function(el){
    element = document.querySelector( el );
    return {
        method1 : function(){
            element.className += " class1";
            return this;
        },
        method2 : function(){
            element.className += " class2";
            return this;
        }
    }
}

这一个完美地用于这样

$e(".myClass").method1().method2();

现在我想更进一步,将这些方法添加到函数的prototype

我基本上不知道怎么做。

我希望它看起来像这样

this.$e = function(el){
    element = document.querySelector( el );
    return element;
}

this.$e.prototype = {
    method1 : function(){
        this.element.className += " class1";
        return this;
    },
    method2 : function(){
        this.element.className += " class2";
        return this;
    }
}

1 个答案:

答案 0 :(得分:0)

我建议从构造函数中提升$e

function myFunction() {
  this.$e = function(el) {
    return new $E(el);
  };

  /* ... */
}

function $E(el) {
  this.element = document.querySelector( el );
}

$E.prototype.method1 = function() {
  this.element.className += " class1";
  return this;
};

$E.prototype.method2 = function() {
  this.element.className += " class2";
  return this;
};
相关问题