如何在javascript中从另一个类调用构造函数
我是JavaScript新手,我想实例化另一个类中的对象 person.js:如何在javascript中从另一个类调用构造函数,javascript,class,constructor,Javascript,Class,Constructor,我是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')); Person在Hello
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'));
Person在Hello.js中未定义
谢谢您应该在
Hello.js
之前插入脚本person.js
,以便定义person
类
差不多
<script src="./person.js"></script>
<script src="./Hello.js"></script>
除非您不在浏览器中(在节点或其他环境中),或者使用诸如browserify之类的依赖关系管理器(例如您隐含的编写var per=require('person');
)
在这种情况下,在
person.js
文件中,添加module.exports=person代码>的末尾,以便它可能是必需的,然后在您的Hello.js
中,使用您需要的变量实例化您的类:newper('mike','smith')
var Person=require('Person')
(否则它将是新的per
),假设这是节点,不要忘记在文件末尾添加module.exports=Person
。谢谢,这对我来说很有效。你很欢迎阅读模块中的节点教程——它应该进一步阐明这一点,并帮助你进一步怀疑。