【问题标题】:How to add methods to prototype如何将方法添加到原型
【发布时间】:2014-03-12 22:59:47
【问题描述】:

所以这是我班级的一部分

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;
    }
}

【问题讨论】:

  • 你如何构造这些对象?
  • @RenatoZannon 你说的构造是什么意思?
  • 如何创建它们?你有构造函数吗?
  • @RenatoZannon 是的,它们在对象内部。这只是一个function myFunction(){ this.$e = ... }。不过,我想在这个函数中使用它们。
  • 为什么要把$e加到this上?

标签: javascript oop prototype


【解决方案1】:

我建议将$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;
};

【讨论】:

  • 实例方法中不需要return this
  • return this 是为了满足链接要求。否则,method1 和 method2 将返回 undefined。
  • 哦,没有注意到链接。我的坏
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2012-06-02
  • 2011-10-20
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多