扩展 jQuery 在每个方法调用上调用构造函数

Extending jQuery calls constructor on each method call

本文关键字:调用 构造函数 方法 jQuery 扩展      更新时间:2023-09-26

我痛苦地试图将jquery扩展到ES6类中,然后用Babel进行转译。除了每次调用继承的jQuery函数之外,一切实际上都可以工作,jQuery似乎每次都调用构造函数。这在这部小提琴中很明显。此外,trigger似乎被叫了 4 次。

(转译代码)https://jsfiddle.net/w3bbzgrn/1/

这是源代码

class Popup extends jQuery.fn.init {
  constructor(t) {
    super(t);
    this.init(t);
    return this;
  }
    test(){
      this.trigger('test', 55)
      return this
    }
}
class Foo extends Popup{
  constructor(t){
    super(t)
    console.log("I get called")
      return this
  }
}
var t = $('<div>hi</div>')
var f = new Foo(t);
f.on('test', function(e,args){
  console.log(args)
})
f.appendTo('body').test().slideUp()
您可以使用

var stack = new Error().stack转储当前调用堆栈,并查看构造函数被调用两次的原因。请参阅更新的 JSFiddle: https://jsfiddle.net/w3bbzgrn/3/

这将打印到控制台:

PRINTING CALL STACK
Error
    at new Foo (VM149:90)
    at window.onload (VM149:102)
I get called
PRINTING CALL STACK
Error
    at new Foo (https://fiddle.jshell.net/_display/:90:15)
    at Foo.pushStack (https://code.jquery.com/jquery-3.0.0.js:141:32)
    at Foo.jQuery.fn.(anonymous function) [as appendTo] (https://code.jquery.com/jquery-3.0.0.js:5920:15)
    at window.onload (https://fiddle.jshell.net/_display/:106:3)
I get called
55

因此,它被调用两次,但在两种不同的情况下:

  1. 第一次,它被称为因为var f = new Foo(t);
  2. 第二次,当使用f.appendTo('body').看起来它试图在附加元素之前创建元素的副本。

也许尝试谷歌搜索类似"jquery append 创建重复项"之类的东西。