How to inherit Common object with other objects in javascript prototype

64 views Asked by At

I am working with javascript. I would like to inherit Common object with other objects in javascript. Is it possible to do it? I mean to convert this js to a prototype model.

function setEvent(evt, ele, callback) {
    var ele = getEle(ele);
    if (ele.length === undefined) {
        ele.addEventListener(evt, callback, false);
    } else if (ele.length > 0) {
        for (var i = 0; i < ele.length; i++) {
            ele[i].addEventListener(evt, callback, false);
        }
    }
    return false;
}

function getEle(ele) {
    var _idf = ele.charAt(0);
    if (_idf == "#") {
        var _ele = document.getElementById(ele.substr(1));
        return _ele;
    } else if (_idf == ".") {
        var _els = document.getElementsByClassName(ele.substr(1));
        return _els;
    }
    return ele;
}

function getInnerHtml(id) {
    return document.getElementById(id).innerHTML;
}

function getValue(elem) {

    return elem.value;

}

setEvent("click", ".input", function() {
    console.log(this.value);
    var _num = getInnerHtml("math");
    _num = _num + "" + getValue(this);
    document.getElementById("math").innerHTML = _num;

});
1

There are 1 answers

2
jfriend00 On BEST ANSWER

It is a bit hard to understand what type of object model you're trying to build since you did not describe any requirements or desires in that regard. Here's one idea that kind of works like jQuery does:

function core(selector) {
    if (!(this instanceof core)) {
        return new core(selector);
    }
    var items = document.querySelectorAll(selector);
    if (items) {
        this.items = Array.prototype.slice.call(items);
    } else {
        this.items = [];
    }
    this.length = this.items.length;
    return this;
}

core.prototype = {
    each: function(fn) {
        for (var i = 0; i < this.length; i++) {
            fn.call(this.items[i]);
        }
        return this;
    },
    firstProp: function(propName, defaultVal) {
        if (this.length > 0) {
            var val = this.items[0][propName];
            return  val !== undefined ? val : defaultVal;
        } else {
            return defaultVal;
        }

    },
    getHTML: function() {
        return this.firstProp("innerHTML", "");
    },
    setHTML: function(html) {
        return this.each(function() {
            this.innerHTML = html;
        });
    },
    on: function(event, fn) {
        return this.each(function() {
            this.addEventListener(event, fn);
        });
    },
    getValue: function() {
        return this.firstProp("value", "");
    }
};

And, then a usage example like yours:

core(".input").on("click", function(e) {
    console.log(this.value);
    var math = core("#math");
    math.setHTML(math.getHTML() + this.value);
});

Working demo: http://jsfiddle.net/jfriend00/t56L4p5f/