Javascript Prototype Chaining super class constructor and method calling

余生长醉 提交于 2019-12-05 08:04:29

Declaring a this.SOME_METHOD in the constructor function doesn't add it to the type's prototype. Prototype functions need to be declared separately, e.g.:

//class parent
function parent(param_1){
    console.log("parent " + param_1);
    this.param = param_1;
}

parent.prototype.getObjWithParam = function(val) {
    console.log("value in parent class "+val);
    console.log("Constructor parameter : "+this.param);
};

//class child
function child(param_1){
    console.log("child " + param_1);
    this.constructor(param_1);
}
child.prototype = new parent();
child.prototype.getObjWithParam = function(val) {
    console.log("value in child class "+val);
    val = Number(val)+1;
    parent.prototype.getObjWithParam.call(this, [val]);    
}

//class grandChild
function grandChild(param_1){
    console.log("grandChild " + param_1);
    this.constructor(param_1);
}
grandChild.prototype = new child();


var gc = new grandChild(666);
gc.getObjWithParam(0);

I would recommend you to read this article, to get a deeper insight how prototypes work in javascript.

Alexander Abashkin

If you want to do chaining (Fluent Interface) like in jQuery:

<div id="div"></div>

<script type="text/javascript">
function $(id) {
    if(this.$) return new $.init(id);
}

$.init = function(id) {
     if(typeof id == 'string') {
         this.id = document.getElementById(id);
     }
};

$.init.prototype = $.prototype = {
    constructor: $,
    css: function(value) {
        for(i in value) {
            this.id.style[i] = value[i];
        }
        return this;
    },
    mush : function() {
        var text = this.id.innerHTML;
        this.id.innerHTML = text.split('').join('--');
        return this;
    },
    text : function(a) {
        this.id.innerHTML = a;
        return this;
    }
};

$('div').text('FOO').mush().css({
        'color' : 'red',
        'textTransform' : 'uppercase'
});
</script>

See example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!