Anderson Green
Anderson Green

Reputation: 31800

Access an inner function from outside the function in Javascript

I'm trying to access an inner function from outside a function in Javascript, but it only prints "undefined" instead of printing the function's source code. How can I modify the prototype of the function changeBlah from outside the scope of exampleFunction?

var blah = "";
function exampleFunction(theParameter){
   this.blah = theParameter;
    this.changeBlah = function(){
        this.blah += "gah";
    }
}

var stuff2 = new exampleFunction("Heh!");
alert(stuff2.blah);
stuff2.changeBlah();
alert(stuff2.blah);

alert(exampleFunction.changeBlah); //now why doesn't this work? It doesn't print the function's source code, but instead prints undefined.​​​​​​​​​​​​​​​​​​​​​​​

Upvotes: 0

Views: 108

Answers (3)

Anderson Green
Anderson Green

Reputation: 31800

This is the best solution that I've devised so far (and it's reasonably concise):

exampleFunction.prototype.changeBlah = function(){
    this.blah += "gah"; //"this" refers to an instance of changeBlah, apparently 
}

var blah = "";
function exampleFunction(theParameter){
   this.blah = theParameter;
}

var stuff2 = new exampleFunction("Heh!");
alert(stuff2.blah);
stuff2.changeBlah(); //it works, even though the "prototype" keyword isn't specifically used here
alert(stuff2.blah);
alert(exampleFunction.prototype.changeBlah);​

Upvotes: 0

user166390
user166390

Reputation:

.. now why doesn't [exampleFunction.changeBlah] work?

Because this was not exampleFunction.

It was a new object which had exampleFunction as the [[prototype]]. Assigning to a property does not propagate back up the [[prototype]] resolution chain. (There is no way to access the [[prototype]] of an object directly from an object, but if the [[prototype]] object is known then it can be mutated.)

Compare with (this will break stuff2.blah, but should show exampleFunction.changeBlah working as expected):

exampleFunction.changeBlah = function(){
    this.blah += "gah";
}

(Also see xdazz's comment for another possible access method.)

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

The closest you can get is by using the Prototype model:

function exampleFunction(theParameter) {this.blah = theParameter;}
exampleFunction.prototype.changeBlah = function() {this.blah += "gah";}

alert(exampleFunction.prototype.changeBlah);

Upvotes: 1

Related Questions