简体   繁体   中英

How to return element object from a function that return an object in javascript?

This is only for learning purpose not for making something else.


In this code below I need some fixing. When I call the superUser('elm') it should return all the specific elements that were given instead of returning whole the objects. Similar to jQuery, (just for learning purpose).

So, It should work like jQuery.

When I called the only superUser('elm') It should return what jQuery return I mean all the elements. Again If I call superUser('elm').on('click', function) it should also work in this case.

 !(function (global, factory) { if (typeof factory === 'function') global.superUser = factory(); }(typeof window !== undefined ? window : this, function () { /** * * @object * Initilize the main object * */ let superUser_fn = {}; /** * @targeted_element * this will give an elm * */ let elm = ''; /** * @superUser * the main function for the project * */ const superUser = function (element) { elm = document.querySelectorAll(element); return superUser_fn; } /** * * @handling_event * This will return an event listener if exist else * it will attach a event for the client * * @arguments * @event = it will give a event for action * @callback = a callback function * */ superUser_fn['on'] = function (event, callback) { if (elm !== null) if (elm.addEventListener) elm.addEventListener(event, callback); else if (elm.attachEvent) elm.attachEvent(event, callback); } /** * * @return * return the full object what ever we work in */ return superUser; })); console.log(superUser('h1'));

const superUser = function (element) {
    elm = document.querySelectorAll(element);
    elm.on = superUser_fn['on'];
    return elm;
}

/**
 * 
 * @handling_event
 * This will return an event listener if exist else
 * it will attach a event for the client
 * 
 * @arguments
 * @event = it will give a event for action
 * @callback = a callback function
 * 
 */

superUser_fn['on'] = function (event, callback) {
    const handler = () => callback(elm)
    if (elm !== null)
        if (elm.addEventListener)
            elm.addEventListener(event, handler);
        else if (elm.attachEvent)
        elm.attachEvent(event, handler);

Not sure if I got your intention..but.. it seems close enough for me to share

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM