0

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.​​​​​​​​​​​​​​​​​​​​​​​
1
  • I just realized that replacing exampleFunction.changeBlah with stuff2.changeBlah prints the function's source. Commented Oct 2, 2012 at 1:40

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

.. 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.)

1 Comment

As the [[constructor]] i think.
0

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);​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.