简体   繁体   English

传递方法时访问javascript实例成员

[英]Accessing javascript instance member when passing the method

I wrote some code like this 我写了一些像这样的代码

function Flasher() {
    this.cards = []
    this.map = {
        14: this.flip
    }
}
Flasher.prototype.flip = function() {
    alert(this.cards.length)
}
flasher = new Flasher()
flasher.map[14]()

Unfortunatley, the this object becomes the map object within the flip method and an error occurs (because cards is undefined). 不幸的是, this对象成为flip方法中的地图对象,并且发生错误(因为cards未定义)。

How can I get this to function as intended? 如何让它按预期运行? Calling flip indirectly via map is necessary, but I would like access to the original object within flip . 通过map间接调用flip是必要的,但我想在flip访问原始对象。

function Flasher() {
    var self = this;

    this.cards = [];
    this.map = {
        14: function() { self.flip(); }
    };
}

Ah the hassles of the protoype pattern 啊原型模式的麻烦啊

I would rewrite it as a module like so: 我会把它重写为像这样的模块:

function flasher() {
  var cards = [],
  flip = function (){
    alert(cards.length)
  },
  map = {
    14: flip
  };

  return {
    cards: cards,
    map: map,
    flip: flip
  };
}

Then the closure captures your scope and you never need to worry about this . 然后关闭捕获您的范围,您永远不必担心这一点 You lose a bit of memory though as your flip function is replicated for each object. 虽然为每个对象复制了翻转函数,但会丢失一些内存。 But I think the code is a lot cleaner and it allows for private variables. 但我认为代码更清晰,它允许私有变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM