javascript模块总是返回undefined

时间:2016-12-14 09:58:00

标签: javascript module undefined

我是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

1 个答案:

答案 0 :(得分:1)

请在new之前加入x.Student,即新x.Student("Dupond","Jean",1835).print();

当执行代码new Foo(...)时,会发生以下情况:

  • 创建一个新对象,继承自Foo.prototype。
  • 使用指定的参数调用构造函数Foo, 并将此绑定到新创建的对象。新的Foo是 相当于新的Foo(),即如果没有指定参数列表,则为Foo 不带参数调用。
  • 构造函数返回的对象成为结果 全新的表达。如果构造函数不起作用 显式返回一个对象,使用在步骤1中创建的对象 代替。 (通常情况下,施工人员不会返回值,但他们可以 如果他们想要覆盖正常的对象创建,请选择这样做 过程。)

您可以找到更多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();