扩展jQuery的类不是它自己的实例
我创建了一个简单的类,它扩展了jQuery. 除了添加一些额外的特定于类的方法之外,它没有做太多事情。问题是,这些方法不能存在,因为对象将自身转换为类型jQuery,而自定义类原型没有了。
这是发生的事情:
class myClass extends jQuery {
constructor(){
super("<div>")
this.append("<a>")
// This works as your would expect
}
createLink(){
this.find("a").attr("href", "//google.com")
}
}
let obj = new myClass();
obj.createLink() // Uncaught TypeError: obj.createLink is not a function
奇怪的是,将原型输出到控制台显示这.createLink 是一个函数:
console.log(myClass.prototype) // {constructor: ƒ, createLink: ƒ}
更奇怪的是,这个对象甚至似乎都不是它自己的一个实例:
class myClass extends jQuery {
constructor(){
super()
}
}
console.log(new myClass instanceof myClass) // false
但其他任何工作:
class myNewClass extends anyOtherObject {
constructor(){
super()
}
}
console.log(new myNewClass instanceof myNewClass) // true
只有当我尝试扩展jQuery. 这是为什么?
回答
不要编写扩展 jQuery 的类。
jQuery 有自己的自定义功能扩展点$.fn,这些自定义扩展称为插件。
一个createLink插件可能是这样的:
$.fn.createLink = function (url) {
$("<a>", {href: url}).appendTo(this);
};
用法:
$("div.bla").createLink("https://www.example.com");
也就是说,全局 jQuery 对象是一个工厂函数,而不是一个构造函数。当您调用 时$("something"),将在内部创建一个新的 jQuery 实例并返回。
扩展工厂函数不会扩展您收到的 jQuery 实例。