0

我在创建我的选择器时遇到了一个问题,我确实需要像在每个 Set Chain 中的 jquery 中一样使用它

var Ary = []; 
var Selector = function(selectorFormant){
// Some Script using querySelectorAll and pushing Elements to Ary
return Ary;
}

Ary.getByTypes=function(typesString){
//Some Script here take the elements inside the Ary and get the elements inside them with the specific types typesString and repush new elements in the Ary
return Ary;
}

        Selector.prototype = Ary;
        Selector.prototype.constructor = Selector;
//this script is responsible for inheritance from Ary to Selector Class

我在这里的问题是开发人员可以通过两种方式使用选择器类

1- Selector.getByTypes('types') 或

2- Selector('selector format like jquery').getByTypes('types')

在 2 中,我不必实例化一个对象来应用我执行的继承,因为方法 Selector 返回具有函数 getByTypes 的 Ary

但是在 1 中,当我不需要开发人员编写新关键字时,我必须从 Selector 实例化一个对象以应用继承来为我拥有 Ary 成员

2 我不需要那个 - new Selector('selector format').getByTypes('types');

任何人都可以帮忙:)

4

2 回答 2

1

看来您真正想要的是:

function Selector(sel) {
    // check if the constructor was used with "new". If not, correct that:
    if (! (this instanceof Selector)) return new Selector(sel);

    // Notice that "this" is an empty object, inheriting from the prototype.
    var els = document.querySelectorAll(sel);
    for (var i=0; i<els.length; i++)
        this.push(els[i]); // use the inherited method "push"
    // even though this is not an actual Array instance

    // Don't return anything, there's an implizit "return this;" as we used "new"
}

// Let the prototype object inherit from Array.prototype
Selector.prototype = Object.create(Array.prototype, {
    constructor: {value:Selector, configurable:true} // and (re)sest constructor
});

// define "getByTypes" method for all instances:
Selector.prototype.getByTypes = function(typ) {
     // Do something with "this"
     …
     // and for chainability return a Selector instance, either a new one or just
     return this;
};

如果你真的需要Selector.getByTypes()——比如“类方法”——你可以在那个属性上添加一个(完全不相关的)函数,做你想做的事:

Selector.getByTypes = function(typ) {
    return new Selector("*").getByTypes(typ); // or anything else
};

…但是,如果在选定的元素中进行搜索,Selector("button")我觉得写作似乎更容易。getByTypes

于 2012-12-11T16:09:20.010 回答
0

querySelectorAll 方法怎么样(虽然只有较新的浏览器支持)?

https://developer.mozilla.org/en-US/docs/DOM/document.querySelectorAll

于 2012-12-11T15:19:05.777 回答