将javascript库转换为链方法

将javascript库转换为链方法,javascript,Javascript,如何重写上面的库,使其像下面那样链接? (function ($) { console.log( $.attr($.getId('foo'), 'data-stuff') // XYZ ); })(Stuff); 专门从代码构建,您可以执行以下操作: 示例: var Stuff=(函数(){ 返回{ 元素:空, getId:函数(id){ this.elem=document.getElementById(id); 归还这个; }, attr:函数(attr,n

如何重写上面的库,使其像下面那样链接?

(function ($) {
    console.log(
        $.attr($.getId('foo'), 'data-stuff') // XYZ
    );
})(Stuff);

专门从代码构建,您可以执行以下操作:

示例:

var Stuff=(函数(){
返回{
元素:空,
getId:函数(id){
this.elem=document.getElementById(id);
归还这个;
},
attr:函数(attr,newVal){
var newVal=newVal | | null;
var ele=this.elem;
if(newVal){
ele.setAttribute(attr,newVal);
}否则{
var attrs=ele.attributes,
attrslen=attrs.length,
结果=ele.getAttribute(attr)| | ele[attr]| | null;
如果(!结果){
对于(变量i=0;i
这将添加一个
elem
属性,该属性存储
getId
的结果。
getId
返回
this
,它是
Stuff
引用的对象,包含所有方法。因此,您可以直接从返回的对象调用
attr

我可以想象,在设置属性时,您希望为
this
attr
包含一个返回值,以便继续链接

<div id="foo" data-stuff="XYZ">Test Div</div>
(function ($) {
    console.log(
        $.attr($.getId('foo'), 'data-stuff') // XYZ
    );
})(Stuff);
(function ($) {
    console.log(
        $.getId('foo').attr('data-stuff') // XYZ
    );  
})(Stuff);
var Stuff = (function() {
    return {
        elem:null,
        getId: function (id) {
            this.elem = document.getElementById(id);
            return this;
        },
        attr: function (attr, newVal) {
            var newVal = newVal || null;
            var ele = this.elem;
            if (newVal) {
                ele.setAttribute(attr, newVal);
            } else {
                var attrs = ele.attributes,
                attrslen = attrs.length,
                result = ele.getAttribute(attr) || ele[attr] || null;

                if (!result) {
                    for (var i = 0; i < attrslen; i++)
                        if (attr[i].nodeName === attr) result = attr[i].nodeValue;
                }
                return result;
            }
        }
    }
})();