传递给构造函数的Can函数可以访问构造函数的其他属性

Can functions passed into constructors have access to the constructor's other properties?

本文关键字:构造函数 访问 属性 其他 Can 函数      更新时间:2023-09-26

通常,调用this可以工作;但是我在另一个上下文中调用该方法,因此this指的是该上下文中而不是"父"对象。

代码如下:

var someConfig = {
  things: [
    {
      attr1: 'foo',
      attr2: 'bar',
      action: function() {
        console.log(this);
      }
    }
  ]
}
function Constructor(config) {
  var self = this;
  self.name = 'test';
  self.things = config.things;
  $.each(self.things, function(i, thing) {
    thing.action();
  });
    }
var obj = new Constructor(someConfig);
console.log(obj);

这里有一个jsfiddle。目标是使控制台上的两个对象相同,但是thisaction方法的上下文中返回action所属的原始对象,而不是构造函数。

我唯一能想到的是将self传递到action,但我认为有更好的方法。

首先,关于代码的几点。您的配置属性是uniqueAction,但稍后您将其称为config.action。当您调用obj.action时,您需要将其作为函数调用,例如:obj.action();

考虑到这一点,以下似乎可以满足您的要求…

var config = {
  action: function() {
    console.log(this.name);//<- IMPORTANT PART
  }
}
function Constructor(config) {
  var self = this;
  self.name = 'test';
  self.action = config.action;
}
var obj = new Constructor(config)
obj.action();

注意console.log调用现在使用this.name而不是self.name

下面是一个工作示例

我看到的唯一方法是在调用action之前将'构造函数'附加到配置thing上。

看看这个小提琴,它是从你的分叉。我改变了两件事:

首先,action函数不再引用this,而是引用this的属性parent

  action: function() {
    console.log(this.parent);
//                  ^^^^^^^
  }

第二,每个thing对象接收一个引用selfparent属性。

  $.each(self.things, function(i, thing) {
    thing.parent = self;
    thing.action();
  });

传递给构造函数的函数可以访问构造函数的其他属性吗?

可以,但只有在将该对象传递给函数(或隐式使用this关键字)时才可以。

您所做的尝试是从构造函数外部声明的函数访问本地self变量,这是不可能的。

使用

{
  action: function() {
    console.log(this.name);
//              ^^^^
  }
}

当调用obj.action()时,this将指向实例