2016-12-14 184 views
0

我是Javascript中的noob,我嘗試實現一個模塊,但每當我在這個模塊中調用一個方法時,它將返回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 
+4

你錯過了'new':'新x.Student( 「杜邦」, 「讓」,1835).PRINT();' –

回答

1

請附上newx.Student之前,也就是新x.Student("Dupond","Jean",1835).print();

當執行代碼的新富(...),下面的事情發生:

  • 創建一個新的對象,從Foo.prototype繼承。
  • 使用指定參數 調用構造函數Foo,並將此綁定到新創建的對象。新的Foo是 等同於新的Foo(),即如果沒有指定參數列表,則調用Foo 而不帶參數。
  • 構造函數返回的對象成爲 全部新表達式的結果。如果構造函數不顯式返回對象,則使用步驟1中創建的對象代替 。 (通常構造函數不返回值,但可以 選擇這樣做,如果他們想覆蓋正常的對象創建 過程。)

你可以找到更多here

"use strict"; 
 
var MODULE=(function(){ 
 
\t var res={}; 
 
\t res.Student=function (name,firstname,id){ 
 
\t \t \t this.name=name; 
 
\t \t \t this.firstname=firstname; 
 
\t \t \t this.id=id; 
 
\t \t \t this.print=function(){ 
 
\t \t \t console.log("student: "+ this.name+', '+this.firstname+', '+this.id); 
 
\t \t 
 
\t \t \t } 
 
\t \t }; 
 

 
\t res.ForeignStudent=function (name,firstname,id,nationalite){ 
 
\t \t \t Student.apply(this,arguments); 
 
\t \t \t this.nationalite=nationalite; 
 
\t \t \t this.print=function(){ 
 
\t \t \t console.log("student: "+ this.name+', '+this.firstname+', '+this.id+', '+this.nationalite) 
 
\t \t \t }; 
 
\t \t }; 
 
\t res.ForeignStudent.prototype = new res.Student(); 
 
\t res.ForeignStudent.prototype.constructor = res.ForeignStudent; 
 
\t return res; 
 

 
}()); 
 
var x=MODULE; 
 
new x.Student("Dupond","Jean",1835).print();

+0

燁,你是對的! 現在真的有用,謝謝! – Akihiko

+0

@明彥請接受它作爲答案,如果它有幫助。謝謝 –