简体   繁体   English

使用 browserify 创建多个对象

[英]creating multiple objects with browserify

I am trying to use the design pattern as below:我正在尝试使用如下设计模式:

human.js人类.js

function Human(name){
    this.name = name
    this.sayName = function(){
         console.log(this.name);
    }
}

var a = new Human("bob");
var b = new Human("ted");

However I haven't used browserify much and I don't know how to do this in browserify.但是我没有经常使用 browserify,我不知道如何在 browserify 中执行此操作。

What I notice is when I require human.js and then try to create a new object, it appears to be replacing the old object.我注意到当我需要 human.js 然后尝试创建一个新对象时,它似乎正在替换旧对象。

How do I use browserify for this design pattern?我如何将 browserify 用于此设计模式?

Rest of my code is something along the lines of:我的其余代码大致如下:

module.exports = {
    MyHuman:Human
}

and in file 1:在文件 1 中:

var human = require('human.js')
var ted = new Human('ted')
ted.sayName();

and in file 2:在文件 2 中:

var human = require('human.js')
var bob = new Human('bob')
bob.sayName();

With CommonJS (Browserify), what you export will be what you get when you call require (however, be careful with assuming what you export is a singleton, it's not always the case from my experience).使用 CommonJS (Browserify),您导出的内容将是您调用 require 时获得的内容(但是,假设您导出的内容是单例时要小心,根据我的经验,情况并非总是如此)。 So in this case, you want to export the Human class directly.所以在这种情况下,你想直接导出 Human 类。 Then in each file that you need to instantiate human, require the class and instantiate from there.然后在您需要实例化人类的每个文件中,需要该类并从那里实例化。

human.js人类.js

function Human(name) {
  this.name = name;
  this.sayName = function() {
    console.log(this.name);
  };
}

module.exports = Human;

file 1文件 1

var Human = require('./human.js');
var ted = new Human('Ted');
ted.sayName();

file 2档案 2

var Human = require('./human.js');
var bob = new Human('Bob');
bob.sayName();

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

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