【问题标题】:Passing parent's scope to a child instance将父范围传递给子实例
【发布时间】:2016-09-07 17:20:22
【问题描述】:

我已经构建了一个演示播放器,可以将其幻灯片创建为 iframe,现在我正在尝试清理我的代码,因为我的原型可以正常工作。不过,我在寻找处理幻灯片和演示播放器之间交互的最佳方式时遇到了问题。幻灯片需要做一些事情,比如告诉播放器他们已经加载或者他们已经完成了播放。

我做了一个播放器和幻灯片实例需要交互的简化示例...

  function Parent() {
    this.child = undefined;
    this.makeChild = function() {
      this.child = new Child(this);
    };
    this.payAttention = function(message) {
      console.log('Child says, "' + message + '"');
    };
  }

  function Child(parent) {
    this.getAttention = function() {
      parent.payAttention('I\'m hungry.');
    };
  }

  var dad = new Parent();
  dad.makeChild();
  dad.child.getAttention();

此模式有效,但我想知道这是否是处理此问题的最有效方法。有没有更好的方法来做到这一点,或者这样可以吗?

【问题讨论】:

  • 对于一个孩子来说,在他们的实例数据中引用他们的父母是完全合理的。你正在做的很好,没有特别好的方法可以做到。
  • 您可以将 child 放入一个匿名函数中,这样可以节省几行...
  • 看起来不错。另一种方法是仅将回调传递给子对象,而不是使用 payAttention 方法的对象。或者为了减少耦合,使用中介。

标签: javascript oop scope


【解决方案1】:

您可以通过将对象插入变量来节省几行代码:

this.child={};
this.makeChild=function(){
a=function(){
this.payAtention("Im Hungry");
}
a.bind(this);
this.child.getAttention=a;
}

如果您从未处理过 .bind(scope): Bind 将作为参数传递的对象绑定到函数内部的 this。

顺便说一句,如果有多个孩子:

this.child=[];
this.child.push({name:"Tim"});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多