【问题标题】:Triggering Instance methods by firing the Parent method通过触发 Parent 方法触发实例方法
【发布时间】:2011-05-28 11:15:50
【问题描述】:

通过调用父级的方法在许多子级中触发方法的最佳方法是什么?

例如,假设我有一个父对象 Foo,它有很多实例:BarX、BarY 等。

Foo = function(){
   x = null;
   y = null;
   move = function(){
      x += 1;
      y += 1;
   };
}

BarX = new Foo();
BarX.x = 50;
BarX.y = 50;

BarY = new Foo();
BarY.x = 200;
BarY.y = 200; 

是否有任何简单的方法可以在所有情况下触发移动功能?我是否仅限于循环遍历实例并触发这样的函数,还是我可以以某种方式触发 Foo 中的函数并让它向下流动并触发所有扩展 Foo 的实例?

【问题讨论】:

  • 只是一个词汇说明:BarX 和 BarY 不是 Foo 的子项,它们是实例。
  • 感谢您的词汇说明。已在原始帖子中修复。

标签: javascript oop function methods instances


【解决方案1】:

没有。但你可以更聪明一点。在Foo 上创建一个静态 moveAll 函数。例子使事情更清楚。 Here is the fiddle.

var Foo = function(x, y){
   this.x = x;
   this.y = y;
   this.move = function(){
      x += 1;
      y += 1;
      alert(x + ' ' + ' ' + y);
   };
   Foo.instances.push(this); // add the instance to Foo collection on init
};
Foo.instances = [];
Foo.moveAll = function(){
    for(var i = 0; i < Foo.instances.length; i++)
        Foo.instances[i].move();
}

var a = new Foo(5, 6);
var b = new Foo(3, 4);

Foo.moveAll();

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2022-10-26
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2012-02-05
    • 1970-01-01
    相关资源
    最近更新 更多