如何在实例中合并模块?

时间:2017-09-14 01:37:50

标签: javascript

我试图找到一种方法来合并或在类中添加模块的某些方法和属性。

function User(data){
  this.name = data.name;
}

User.prototype.sayHello = function(){
  return this.name+' says hello.';
}

module.exports = User;

我想在玩家类加入游戏示例后,向我的用户添加一些属性和方法。

function Player(user){
  this.chances = 3;
}

Player.prototype.run = function(){
 return this.name+' is running.';
}

我尝试使用subClass,但是我从User中删除了所有参数并且只有Player的参数。我想做这样的事情:

var user = new User({name:Jacques});

user.sayHello() // Jacques says hello.

user.becomePlayer();

user.run(); // Jacques is running.

或者是否可以向用户变量添加属性和方法?

user.becomePlayer() // user now can run.

3 个答案:

答案 0 :(得分:0)

如果你想在对象用户上添加一个方法,你可以这样做:

User.prototype =  {
    sayHello : function(){
        return this.name+' says hello.';
    },
    becomePlayer: function () {
        //do some thing
    }
}

如果用户想要访问播放器的方法,可以使用继承( 原型链继承):

User.prototype = new Player();
var user = new User({name: 'Jacques'})

console.log(user.run());//Jacques is running.

答案 1 :(得分:0)

如果您希望User的实例从Player接收通常称为 mixins 的内容(这是JavaScript的ad-hoc接口术语),您可以执行以下操作,我不建议

function User(data) {
  this.name = data.name;
}

User.prototype.sayHello = function() {
  return this.name + ' says hello.';
}

User.prototype.becomePlayer = function() {
  Object.assign(this, Player.prototype);
  Player.call(this);
  
  return this;
}

function Player() {
  this.chances = 3;
}

Player.prototype.run = function() {
  return this.name + ' is running.';
}

var user = new User({ name: 'Jacques' });

console.log(user.sayHello());
user.becomePlayer();
console.log(user.run());

如果您需要推荐方法,只需将Player扩展User并构建Player的实例即可开始,如下所示:

function User(data) {
  this.name = data.name;
}

User.prototype.sayHello = function() {
  return this.name + ' says hello.';
}

function Player(data) {
  User.call(this, data);

  this.chances = 3;
}

Player.prototype = Object.create(User.prototype);
Player.prototype.constructor = Player;

Player.prototype.run = function() {
  return this.name + ' is running.';
}

var user = new Player({ name: 'Jacques' });

console.log(user.sayHello());
console.log(user.run());

答案 2 :(得分:-1)

这可能是一个可能的解决方案,但不是100%适合您的情况。



function User(data){
  this.name = data.name;
}

User.prototype.sayHello = function(){
  this.name+' says hello.';
}

function Player(user){
  this.chances = 3;
}

var run = function(){
   console.log(this.name + ' is running.');
}

User.prototype.becomePlayer = function() {
  return Object.assign(User.prototype, {run});
}

//console.log(Player.prototype.run);
var tom = new User({name: "Tom"});
tom.becomePlayer();
tom.run();