我是JavaScript的新手,我想从另一个类实例化一个对象。
person.js:
function Person(first,last){
this.first = first;
this.last = last;
}
Person.prototype = {}
Hello.js:
var per = require('person');
var persons = [];
persons.push(new Person('mike','smith'));
在Hello.js中未定义Person。
由于
答案 0 :(得分:0)
您应该在person.js
之前插入脚本Hello.js
,以便定义Person
类。
像
这样的东西<script src="./person.js"></script>
<script src="./Hello.js"></script>
除非你不在浏览器中(在节点或其他环境中),或者使用像browserify这样的依赖管理器(就像你暗示写var per = require('person');
)
在这种情况下,在person.js
文件中,在最后添加module.exports = Person;
以便可能需要它,然后在Hello.js
中,使用您需要的变量来实现课程:new per('mike','smith');