javascript - 创建类似 jquery 函数链的动态原型(prototype)

标签 javascript jquery

我尝试创建一个像 jQuery 一样的动态原型(prototype)并且能够函数链,但是我在没有使用 new 和函数内部时出错,返回 this 对象正确吗?

    (function() {
      var peopleDynamicProto = function(name, age, state) {

        this.name = name;
        this.age = age;
        this.state = state;

        if (typeof this.printPerson !== 'function') {
          peopleDynamicProto.prototype.printPerson = function() {
            console.log(this.name + ',' + this.age + ',' + this.state);
            return this;
          };
        }

        if (!this.hasOwnProperty('gender')) {
          peopleDynamicProto.prototype.gender = 'male';
          return this;
        }
      }

      window.peopleDynamicProto = peopleDynamicProto;
      return peopleDynamicProto;

    })();

     //var person1 = new peopleDynamicProto('john', 23,'CA');
     //person1.printPerson();

    peopleDynamicProto('john', 23, 'CA').printPerson(); //got error

谁知道问题出在哪里?

最佳答案

如果你想创建一个基于原型(prototype)的新对象,你必须使用“new”。 我不确定您到底要做什么,以及为什么要尝试动态创建原型(prototype)。我不会说 100% 肯定,但我不认为 jQuery 会那样做(而且这看起来是一种非常糟糕的做法)。 如果你想做一些像 jQuery 这样的事情,你的类是可链接的并且可以链接为 (new peopleDynamicProto(...)).print()peopleDynamicProto(... ).print(),那么你可以这样做:

function peopleDynamicProto(name) {
  if (this instanceof peopleDynamicProto) {
    /* initialize attributes here */
    this.name = name;
  } else {
    return new peopleDynamicProto(name);
  }
}

peopleDynamicProto.prototype.printPerson = function() {
   console.log( this.name );
   return this;
}

现在你应该可以用两种方式调用它了:

peopleDynamicProto('john').printPerson();
(new peopleDynamicProto('john')).printPerson();

如果你不关心支持这两种方式,那么你可以只返回一个对象,例如:

function peopleDynamicProto(name) {
  return {
    name: name,
    printPerson = function() {
      console.log( this.name );
      return this;
    }
  };
}

peopleDynamicProto('John').printPerson();

(还有其他方法)

关于javascript - 创建类似 jquery 函数链的动态原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41318453/

相关文章:

javascript - 如何将最长元素的宽度分配给其他元素

javascript - 获取 document.getElementsByClassName 的子类

javascript - 为什么YouTube Player API循环无效?

javascript - 使用javascript排序函数根据条件对数组进行排序

javascript - 当鼠标悬停在文本中的单词上时显示警报

javascript - 如何与其他 ReactDOM.render 进行 ReactDOM.render 通信

jQuery如何在溢出隐藏框上显示div

javascript - primefaces 更新页面的 <head> 内容

javascript - 如何使用javascript通过id隐藏html div

javascript - 下拉/组合框的已选项目应反射(reflect)为单击标签时的选定项目