0

我正在尝试从 Javascript 中的函数外部访问内部函数,但它只打印“未定义”而不是打印函数的源代码。如何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.​​​​​​​​​​​​​​​​​​​​​​​
4

3 回答 3

1

最接近的方法是使用 Prototype 模型:

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

alert(exampleFunction.prototype.changeBlah);
于 2012-10-02T01:42:06.317 回答
0

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

因为this 不是 exampleFunction

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

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

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

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

于 2012-10-02T01:41:29.600 回答
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);​
于 2012-10-02T03:15:05.117 回答