简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM