在“原型”函数的不同级别内访问函数的属性 - 和 - 递归函数

时间:2013-08-10 13:35:34

标签: javascript recursion scope prototype

好的,这让我困惑了好几天!假设我有类似的东西:

var FooBar = function(args) {
   this.annoy = typeof args == "boolean" ? args : false;
   this.Foo();
}

FooBar.prototype.Foo = function() {
   if (this.annoy)
      window.alert("My name is Foo!")
   else
      window.console.log("My name is Foo!")
   this.Bar()
}

FooBar.prototype.Bar = function() {
   if (this.annoy)
      window.alert("My name is Bar!")
   else
      window.console.log("My name is Bar!")
}

这很好用。但是,如果将Bar()定义为另一个对象的属性(又是FooBar的{​​{1}}的属性),有什么办法可以在新版本中访问prototype annoy而不必将Bar()作为参数传递给它?例如:

annoy

我可能错了,但我确信在FooBar.prototype.evenDeeper = { Bar: function() { // I wish to access "annoy" here! }, anotherOne: function() { }, yetAnotherOne: 'value' } 内,Foo()会被称为Bar(),不是吗?而且,如果this.evenDeeper.Bar()想要递归怎么办? Bar()会将自己称为Bar()本身,还是Bar()Foobar.evenDeeper.Bar()或什么?

摘要

  1. 如果this.Bar()内有Bar() annoy evenDeeper怎么办?
  2. Bar()本身如何引用自身?

  3. 免责声明:我甚至远程计划用alert() s来烦扰任何人! ;)

1 个答案:

答案 0 :(得分:1)

1。 A)将变量传递给evenDeeper.Bar; B)使用evenDeeper.bar.apply(new FooBar(args))使用'this'访问FooBar原型; C)为这个FooBar.annoy变量赋予evenDeeper.annoy(不推荐使用,因为布尔值是按值传递的,它不会反映对它的更改)

2。 A)在evenDeeper.Bar()中使用this.Bar(),除非你改变了'this'变量,否则它应该引用它自己。 B)传递this.Bar作为对this.Bar()的回调并在其自身内执行 C)在函数上下文中声明this.Bar(),以便它可以简单地将自己称为Bar(),例如:

FooBar.prototype.evenDeeper = (function () {
    function Bar() {
        if (this.annoy) {
            alert('are you annoyed yet?');
        }
        Bar.apply(this);
    }
    return {
        Bar: Bar,
        anotherOne: function () {},
        yetAnotherOne: function () {}
    };
}());

var test = new FooBar(true);
// WARNING: this will never finish!
test.evenDeeper.Bar.apply(test);

这是一个通用的解决方案,如果您发布了更具体的内容,那么很可能有更好的方法来实现您想要的效果。就个人而言,我会避免创建一个依赖于其所在命名空间的函数。