Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从连接到原型的对象中访问实例变量_Javascript_Node.js - Fatal编程技术网

Javascript 从连接到原型的对象中访问实例变量

Javascript 从连接到原型的对象中访问实例变量,javascript,node.js,Javascript,Node.js,在附加到协议之前,我需要将实例方法分组到一个对象中 但当我这样做时,“this”现在指向对象,我无法访问实例变量。 请参见下面的代码进行说明 var events = require('events'); var Matcher = function Matcher(){ this.list3 = []; events.EventEmitter.call(this); }; require('util').inherits(Matcher, events.EventEmitter

在附加到协议之前,我需要将实例方法分组到一个对象中 但当我这样做时,“this”现在指向对象,我无法访问实例变量。 请参见下面的代码进行说明

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();
它给出了一个错误,因为this.vars.list1和this.list3都未定义。 很可能是因为这指向的是protocols对象,而不是原型

如果您能提供变量参考,我将不胜感激

我试过以下方法

matcher.protocols.add( matcher, 'new item');
然后在add函数中,我使用matcher来代替这个。
但我认为这是错误的。

您可以重新排列函数定义,将定义包含在
匹配器的范围内。这将允许您定义一个等于
This
的私有变量,然后可以在
vars
protocols
定义中访问该变量

例如:

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();
产出:

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