简体   繁体   English

从附加到原型的对象中访问实例变量

[英]Access instance variables from within object attached to prototype

I need to group instance methods into an object before attaching to the protocol But when I do that, "this", now points to the object and I can't access instance variables. 在连接到协议之前,我需要将实例方法分组为一个对象,但是当我这样做时,“ this”现在指向该对象,并且我无法访问实例变量。 Please see the following code for Illustration. 请参见以下代码以获取插图。

var events = require('events');
var Matcher = function Matcher(){
    this.list3 = [];
    events.EventEmitter.call(this);
};
require('util').inherits(Matcher, events.EventEmitter);

Matcher.prototype.vars = {
  list1 : [ 1, 2 ],
  list2 : [ 'foo', 'bar' ]
};


Matcher.prototype.protocols = {

  print : function(ref){
    console.log(" lists : ", this.list1, this.list2, this.list3 );
  },

  add   : function(item){
    this.vars.list1.push(item);
    this.list3.push(item);
  }

};

var matcher = new Matcher();

matcher.protocols.add( 23 );
matcher.protocols.print();

It gives an error, because this.vars.list1 and this.list3 are both undefined. 因为this.vars.list1和this.list3都未定义,所以会给出错误。 Most likely because this points to the protocols object and not the prototype. 最有可能的原因是,这指向协议对象而不是原型。

I would appreciate any help on getting a reference to the variables. 我会很高兴获得对变量的引用。

I have tried the following 我尝试了以下

matcher.protocols.add( matcher, 'new item');

then in the add function i do this, I use matcher in place of this. 然后在添加功能我做到这一点,我用匹配器代替它。 But this looks wrong to me. 但这对我来说似乎是错误的。

You can rearrange your function definitions to include the definitions within the scope of Matcher . 您可以重新排列函数定义,使其包含在Matcher范围内。 This will allow you to define a private variable equal to this , which you can then access within the vars and protocols definitions. 这将允许您定义一个等于this的私有变量,然后可以在varsprotocols定义中访问this私有变量。

So for instance: 因此,例如:

var events = require('events');
var Matcher = function Matcher(){
    this.list3 = [];
    events.EventEmitter.call(this);

    this.vars = {
      list1 : [ 1, 2 ],
      list2 : [ 'foo', 'bar' ]
    };

    var matcher = this;
    this.protocols = {

      print : function(ref){
        console.log(" lists : ", matcher.vars.list1, matcher.vars.list2, matcher.list3 );
      },

      add : function(item){
        matcher.vars.list1.push(item);
        matcher.list3.push(item);
      }

    };

};
require('util').inherits(Matcher, events.EventEmitter);


var matcher = new Matcher();

matcher.protocols.add( 23 );
matcher.protocols.print();

Outputs: 输出:

 lists :  [ 1, 2, 23 ] [ 'foo', 'bar' ] [ 23 ]

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

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