SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Feb 2007
    Location
    Leeds, U.K.
    Posts
    127
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:

    Code:
    <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!

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    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:

    Code javascript:
    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:

    Code javascript:
    Obj.prototype._init = function () {
        oldInit.call(this);
        newInit.call(this);
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Zealot
    Join Date
    Feb 2007
    Location
    Leeds, U.K.
    Posts
    127
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excellent, just what I was looking for!

    Thanks pmw57


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •