【问题标题】:Inherit jquery object继承 jquery 对象
【发布时间】: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


【解决方案1】:

似乎没有向ValueCounter 添加其他属性,最简单的方法是将jQuery 别名为ValueCounter,使用$.fn.extenddataCounter 设置为jQuery object 的方法。另见Building staeful jQuery plugins

var ValueCounter = jQuery;
$.fn.extend({
  dataCounter: function() {
    console.log(this.data("counter"));
    return this
  }
});

var toto = new ValueCounter("body");
toto.dataCounter();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body data-counter="0">

要求:

  • 我会创建一个继承自 jQuery 的对象。

  • 仅在该对象上添加函数和/或属性。

  • 像 jQuery 对象一样使用我的对象 (myObject.addClass(...))

尝试使用for循环将jQuery属性设置为对象,别名fn.init()$对象

var obj = Object.create({
  "abc": 123,
  "color":"olive",
  "def": function() {
    return this.abc
  },
  "el": "body",
  "method": function() {
    return this
  }
});

for (prop in window["jQuery"]) {
  // alias `$` to `fn.init` at `obj`
  if(prop === "fn") { obj["$"] = window["jQuery"][prop].init };
  obj[prop] = window["jQuery"][prop]
}

obj.$(obj.el)
.html(obj.abc)
.css("color", obj.color);

console.log(obj.method())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>abc</body>

【讨论】:

  • 感谢您的解决方案,但这并不是我想要的。因为在这种情况下,所有的jquery对象都可以使用这个函数。 $('mySelector').dataCounter(); // 这段代码有效,但我不会
  • @MatthieuKaiser 不确定问题的要求是什么?