共享'这'文件之间

Sharing 'this' between files

本文关键字:之间 文件 共享      更新时间:2024-01-13

我正在创建一个有很多方法的对象,并试图避免我的文件太长。问题是有些方法引用了对象中的其他信息。我希望能够做这样的事情:

index.js

var User = function(first, last){
  this.firstname = first;
  this.lastname = last;
};
User.prototype.name = require('./methods/name.js')

methods/name.js

module.exports = {
  full: function(){
      return this.firstname + " " + this.lastname;
  },
  formal: function(){
      return "Mr. " + this.lastname;
  }
};

为什么this在这种情况下不起作用是有道理的,但是否有不同的解决方案可以引用其他文件?我唯一能想到的是使用fs和eval()而不是require,但这对我来说似乎是一个黑客攻击,或者显然是有一个长文件。有更好的吗?

我计划在原型上有大约35个对象,每个对象平均有4个方法。建议?谢谢

问题与它在单独的文件中无关。如果你这样定义用户,你会在一个文件中遇到同样的问题:

var User = function(first, last){
  this.firstname = first;
  this.lastname = last;
};
User.prototype.name = {
  full: function(){
      return this.firstname + " " + this.lastname;
  },
  formal: function(){
      return "Mr. " + this.lastname;
  }
};

因为当您调用someuser.name.full()时,this将绑定到someuser.name而不是someuser

如果您不需要为这些函数命名名称空间,并且这样做只是因为您不确定如何从另一个文件扩展原型,那么您可以使用Object.assign:

Object.assign( User.prototype, require('./methods/name.js') );

然后您可以调用someuser.full()someuser.formal(),当然this将具有正确的值。

您可以绑定这样的函数:

User.prototype.name = require('./methods/name').bind(this)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

bind()方法创建一个新函数,当调用该函数时该关键字设置为提供的值,具有给定的在调用新函数时提供的任何参数之前的参数。

此外—;在您的请求路径中丢失.js

这应该会使您的代码保持模块化

//index.js

var userMethods = require('.methods/name.js');
var User = function(first, last){
  this.firstname = first;
  this.lastname =  last;
};
User.prototype.name = userMethods.full;
User.prototype.formalName = userMethods.formal;
var Abbey = new User('Abbey', 'Jack');
console.log(Abbey.firstname); // Abbey
console.log(Abbey.lastname); // Jack
console.log(Abbey.name()); // Abbey Jack
console.log(Abbey.formalName()); // Mr. Jack

//methods/name.js

module.exports = {
  full: function(){
      return this.firstname + " " + this.lastname;
  },
  formal: function(){
      return "Mr. " + this.lastname;
  }
};