如何声明自定义JavaScript库的方法的缩写?

如何声明自定义JavaScript库的方法的缩写?,javascript,methods,javascript-objects,alias,declare,Javascript,Methods,Javascript Objects,Alias,Declare,我想知道如何为JavaScript库中的方法创建别名速记 我的库的方法声明的结构如下: myLib = function(selector){ var x, obj = { slct(selector){ // ... the method itself ... }, attr(a,b){ if(x){ // ... the method itself ... return this } }, class(

我想知道如何为JavaScript库中的方法创建别名速记

我的库的方法声明的结构如下:

myLib = function(selector){

  var x, obj = {

   slct(selector){
    // ... the method itself ...
   },

   attr(a,b){
    if(x){
      // ... the method itself ...
      return this
    }
   },

   class(a,b){
     if(x){
       // ... the method itself ...
       return this
     }
   },

   data(a,b){
    if(x){
      // ... the method itself ...
      return this
    }
   },

   style(a,b){
      if(x){
        // ... the method itself ...
        return this
      }
    }

    // ... and many more ...

  };
  x = obj.slct(selector);
  return obj
}
myLib('#someDOMelement').attr('href','https://domain.tld/subpage');
myLib('#someDOMelement').class('someNewClass');
myLib('#someDOMelement').data('someDataSet');
myLib('#someDOMelement').style('background','#000');
我这样称呼我的方法:

myLib = function(selector){

  var x, obj = {

   slct(selector){
    // ... the method itself ...
   },

   attr(a,b){
    if(x){
      // ... the method itself ...
      return this
    }
   },

   class(a,b){
     if(x){
       // ... the method itself ...
       return this
     }
   },

   data(a,b){
    if(x){
      // ... the method itself ...
      return this
    }
   },

   style(a,b){
      if(x){
        // ... the method itself ...
        return this
      }
    }

    // ... and many more ...

  };
  x = obj.slct(selector);
  return obj
}
myLib('#someDOMelement').attr('href','https://domain.tld/subpage');
myLib('#someDOMelement').class('someNewClass');
myLib('#someDOMelement').data('someDataSet');
myLib('#someDOMelement').style('background','#000');
但我想声明我的方法的别名,例如:

myLib('#someDOMelement').a('href','https://domain.tld/subpage');
myLib('#someDOMelement').c('someNewClass');
myLib('#someDOMelement').d('someDataSet');
myLib('#someDOMelement').s('background','#000');
我怎么能这样做

我现在看到的唯一方法是第二次声明整个方法,我想这不是最有效的方法D


谢谢你在这方面的帮助!:)

由于您正在为每次调用
myLib
创建对象,并且依赖于函数关闭
x
,因此除了涉及访问器的快捷方式(在答案的下面),没有真正的快捷方式(没有双关语),您只需在创建
obj
后设置这些属性:

  // ...
  obj.a = obj.attr;
  obj.c = obj.class;
  obj.d = obj.data;
  obj.s = obj.slct;
  x = obj.slct(selector);
  return obj
}
或者您可以使用循环,但它似乎不太可维护:

  // ...
  for (const name of ["attr", "class", "data", "slct"]) {
      obj[name.charAt(0)] = obj[name];
  }
  x = obj.slct(selector);
  return obj
}
另一种方法是使用带有
a
等的访问器属性的原型,但它添加了另一个函数调用(通常并不重要):


您应该使用原型,然后可以分配
myLib.prototype.a=myLib.prototype.attr
。如果每个对象都有这些方法,那就没有简单的方法了。非常感谢!你的回答在整个话题上对我帮助很大!:)