跳到主要内容
CNode

require 一个模块的 new 问题

社区
Llianxuan发布于 12 年前最后回复 12 年前
359770
//module.js
var name;

exports.setName = function(thyName) {
    name = thyName;
};

exports.sayHello = function() {
    console.log('Hello ' + name);
};

//getmoudle.js

var myModule = require('./module');

myModule.setName('BYVoid');
myModule.sayHello();

//hello.js

function Hello() {
    var name;

    this.setName = function(thyName) {
        name = thyName;
    };

    this.sayHello = function() {
        console.log('Hello ' + name);
    };
};

module.exports = Hello;

//gethello.js

var Hello = require('./singleobject');

hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();

这里第一个 require 一个模块后不需要 new,第二个为什么要 new一个呢?请教各位大神一下,谢谢

查看回复

回复 (3)

A
alsotang#312 年前

这不是 require 的知识范畴。应该去看看 js 里面的 new 是干嘛的。

L
lianxuan#212 年前

好的,谢谢回复了

1
151263#112 年前

也可以不用 new 的, new 到底是干嘛的, 是 JavaScript 的基本语法, 你可以去学习 JavaScript 关于原型 prototype 的基础知识

jsfunction dog() {
   this.wanwan = function(){
      alert("汪汪");
  };
}
var dg = new dog();
dg.wanwan();

参与回复

登录后即可参与回复。登录