0

The reason of the question is the same as Adding code to a javascript function programmatically: I'm attempting to customize an existing JS library without significant modifications the original JS code.

There is the code:

function A(){
}

A.prototype.foo = function(smth) {
    function bar(smth) {
        alert("I'm bar inside foo " + smth);
    }

    bar(smth);
}

a = new A;
a.foo("hello");

I'd like to add some code into bar programatically. According to Javascript call nested function I slightly change the code and try Adding code to a javascript function programmatically:

function A(){
}

A.prototype.foo = function(smth) {
    function bar(smth) {
        alert("I'm bar inside foo " + smth);
    }

    this.foo.bar = this.foo.bar || bar; // make bar visible from outside

    this.foo.bar(smth);
}

// A.prototype.foo(); // XXX the code doesn't work correctly without that line

// add code into the bar
A.prototype.foo.bar = (function() {
var cached_function = A.prototype.foo.bar;

return function() {
    alert("I'm an addition for bar before");
    var result = cached_function.apply(this, arguments); 
    alert("I'm an addition for bar after");

    return result;
};
})();

a = new A;
a.foo("hello");

but the code doesn't work without the XXX line. I guess that A.prototype.foo.bar is undefined until the A.prototype.foo() call, but I mustn't do the call (because foo() is doing something). The solution is check inside foo if this is null etc.

But is there more elegant and right solution? I will appreciate any help.

Community
  • 1
  • 1
Mikhail V.
  • 75
  • 8

1 Answers1

0

because foo is a function. In order to what you want to do

A.prototype.foo = {
bar: function() {
    alert("I'm bar inside foo");
}
bar();

}

erdysson
  • 1,450
  • 13
  • 17
  • If you do this, you won't be able to do `a.foo()` any more, because `foo` is an object, not a function. – Barmar Dec 11 '15 at 23:45