使用可变的参数计数调用类对象

时间:2014-12-29 23:42:42

标签: javascript function class arguments prototype

我正在为一个非常具体的任务创建自己的jQuery类库。 (不想使用jquery,更接近原生js)。

我需要一个解决方案来调用带有和没有agruments的类,在我的情况下 - 某个选择器。

我的想法 - 班级必须以两种方式工作:

myclass.function();

myclass(selector).function();

类的初始化看起来像这样

(function(window){
var myclass = function( selector ){
        return new myclass.model.build( selector );
    };

myclass.model = myclass.prototype = {
    constructor: myclass,
    myfunction: function(){
        alert("some function's alert");
    }
};

myclass.model.build = function( selector ){
    if( !selector )
        return this;
    /* Picking objects by selector */
};

window.myclass = myclass;
return myclass;
})(window);

2 个答案:

答案 0 :(得分:2)

<强> jsFiddle Demo

有几种方法可以实现这一目标。这是一种常见的方法,即设置本地函数(“类”)的实例,该实例将其原型配置为可扩展性对象,并将属性作为对象附加到其中。

//use window and document shortcut
(function(win,doc){
 //setup local function in order to extend
 var jakeWeary = function(selector){
  //force an instance to be returned when referenced
  return new jakeWeary.fun.start(selector);        
 };
 //allow prototype to be extended by referencing fun
 jakeWeary.fun = jakeWeary.prototype = {
  constructor : jakeWeary,
  //use passed values to query
  start : function(selector){
   //query against present document
   var nodes = doc.querySelectorAll(selector);
   //mimic an array of matched elements
   for(var i = 0; i < nodes.length;i++){
    this[i] = nodes[i];       
   }
   //return self for chaining
   return this;     
  }
 };
 //extend function object in order to be used without calling instance
 jakeWeary.div = function(content){
  var div = document.createElement("div");
  div.innerHTML = content;
  return div; 
 };
 //expose
 win.jakeWeary = win.jk = jakeWeary;
})(window,document)

//call instance to match the selector `.d`
var $ = jakeWeary('.d');//lets use a fun variable like $ for this
//reference the third matched element, and then append a div created from a function on the
//jakeWeary function object
$[2].appendChild(jk.div("<p>Reinventing the wheel</p>"));
<div id="i">i</div>
<div class="d">d</div>
<div class="d">d</div>
<div class="d">d</div>

答案 1 :(得分:1)

您的意思是您希望非实例调用生成默认实例然后应用于它?

var Foo = (function () {
    // set up constructor
    var Foo = function () {
        this.fizz = 'buzz';
    };
    Foo.prototype = Object.create(null);
    // instance version
    Foo.prototype.bar = function () {return 'this.fizz is ' + this.fizz;};
    // non-instance version
    Foo.bar = function () {return Foo.prototype.bar.apply(new Foo(), arguments);};
    return Foo;
}());

Foo.bar(); // "this.fizz is buzz"