我是Javascript中的菜鸟,我尝试实现一个模块,但每当我在这个模块中调用一个方法时,它都返回undefined。
请帮忙!
"use strict";
var MODULE = (function() {
var res = {};
res.Student = function(name, firstname, id) {
this.name = name;
this.firstname = firstname;
this.id = id;
this.print = function() {
console.log("student: " + this.name + ', ' + this.firstname + ', ' + this.id);
}
};
res.ForeignStudent = function(name, firstname, id, nationalite) {
Student.apply(this, arguments);
this.nationalite = nationalite;
this.print = function() {
console.log("student: " + this.name + ', ' + this.firstname + ', ' + this.id + ', ' + this.nationalite)
};
};
res.ForeignStudent.prototype = new res.Student();
res.ForeignStudent.prototype.constructor = res.ForeignStudent;
return res;
}());
var x = MODULE;
x.Student("Dupond", "Jean", 1835).print(); // Cannot read property 'print' of undefined
答案 0 :(得分:1)
请在new
之前加入x.Student
,即新x.Student("Dupond","Jean",1835).print();
当执行代码new Foo(...)时,会发生以下情况:
您可以找到更多here。
"use strict";
var MODULE=(function(){
var res={};
res.Student=function (name,firstname,id){
this.name=name;
this.firstname=firstname;
this.id=id;
this.print=function(){
console.log("student: "+ this.name+', '+this.firstname+', '+this.id);
}
};
res.ForeignStudent=function (name,firstname,id,nationalite){
Student.apply(this,arguments);
this.nationalite=nationalite;
this.print=function(){
console.log("student: "+ this.name+', '+this.firstname+', '+this.id+', '+this.nationalite)
};
};
res.ForeignStudent.prototype = new res.Student();
res.ForeignStudent.prototype.constructor = res.ForeignStudent;
return res;
}());
var x=MODULE;
new x.Student("Dupond","Jean",1835).print();