Overwriting a prototype function and keeping scope

Hi,

Not sure if this is possible, but I have an external script that creates an object, and I want to overwrite some of its functionality, but keep the scope.

Here is a basic example:


<script>
            Obj = function (userConfig) {
                this._init(userConfig);
            };

            Obj.prototype = {
                _init: function () {
                    console.log(this);
                }
            };

            var oldInit = Obj.prototype._init;
            var newInit = function() {
                console.log(this);
            }
            Obj.prototype._init = function() {
                oldInit();
                newInit();
            }
            var testObj = new Obj();
        </script>

I want it to log two Objects, but instead I get two window elements. Is this because I am declaring the functions in the global scope, and not from within the object?

Anyway I can keep the scope of the object, whilst still overwriting the function?

Cheers!

The this keyword is not being maintained when the _init function calls another function. That is expected behaviour.

The oldInit and newInit functions are members of the window object. If you want them to have the context of the object, you could add them to the prototype as you did with _init and then invoke them:


Obj.prototype.oldInit = ...
Obj.prototype.newInit = ...
Obj.prototype._init = function () {
    this.oldInit();
    this.newInit();
}

An alternative technique which means you don’t need to attach those other functions on to the object, is to pass the context to the function’s call method:


Obj.prototype._init = function () {
    oldInit.call(this);
    newInit.call(this);
}

Excellent, just what I was looking for!

Thanks pmw57