【发布时间】:2025-12-07 21:00:02
【问题描述】:
我需要从一个 jQuery 对象继承来创建我自己的具有附加功能的对象。
我已经用两个自定义对象尝试过这个并且它有效:
var MotherClass = function(name){
this.name = name;
}
MotherClass.prototype.getName = function(){
console.log(this.name);
};
var mother = new MotherClass("mam");
mother.getName(); //=> mam
var ChildClass = function(propName){
MotherClass.call(this, propName);
}
ChildClass.prototype = Object.create(MotherClass.prototype);
ChildClass.prototype.getChildName = function(){
console.log(this.name + " child");
};
var child = new ChildClass("child");
child.getName(); //=> child
child.getChildName(); //=> child child
子类正确调用母类的构造函数。现在我想用 jQuery 做同样的事情。
但是用jQuery,我不知道怎么调用jQuery的构造函数...
var ValueCounter = function (selector) {
$.call(this, selector);
}
ValueCounter.prototype = Object.create(jQuery.prototype);
ValueCounter.prototype.dataCounter = function(){
console.log(this.data('counter'));
// => this is equals to [] and not my div;
//so the return is "undefined" and note the value of my data.
};
var toto = new ValueCounter("#toto");
toto.dataCounter();
编辑:
要求:
我会创建一个继承自 jQuery 的对象。
仅在此对象上添加函数和/或属性。
像 jQuery 对象一样使用我的对象 (myObject.addClass(...))
我希望这些功能最简单地使用我的对象,而不是在属性“$element”中创建一个简单的对象,因为你一直在写:myObject.$element.jQueryFunctions。太长了。
我只想写:
myObject.jQueryFunctions
myObject.personnelFunctions
myObject.personnelProperties
【问题讨论】:
-
为什么需要这样做?可能有更好的方法....
-
我更喜欢从我的 jquery 对象继承,因为最容易编写代码: var toto = new ValueCounter("#toto"); toto.addClass("myClass");添加不要这样写:toto.$element.addClass("myClass");我只会为这种元素而不是所有 jquery 对象添加函数。
标签: javascript jquery oop