在Javascript中从函数外部访问内部函数

时间:2012-10-02 01:38:40

标签: javascript

我正在尝试从Javascript中的函数外部访问内部函数,但它只打印“undefined”而不是打印函数的源代码。如何在changeBlah范围之外修改函数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.​​​​​​​​​​​​​​​​​​​​​​​

3 个答案:

答案 0 :(得分:1)

最接近的是使用Prototype模型:

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

alert(exampleFunction.prototype.changeBlah);

答案 1 :(得分:0)

  

..现在为什么不[exampleFunction.changeBlah]工作?

因为this 不是 exampleFunction

这是一个新对象,其中exampleFunction为[[prototype]]。分配给属性不会传播回[[prototype]]解析链。 (无法直接从对象访问对象的[[prototype]],但如果[[prototype]]对象已知那么它可以是突变。)

比较(这会中断stuff2.blah,但应显示exampleFunction.changeBlah按预期工作):

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

(另请参阅xdazz对另一种可能的访问方法的评论。)

答案 2 :(得分:0)

这是我迄今为止设计的最佳解决方案(而且相当简洁):

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