2013-01-09 24 views
0

我剛開始在JavaScript製作上課的時候是不是一個函數錯誤,這是我創造的東西就像我的第一類:*創建在JavaScript中的一類

function MessageBox(parent){ 
    this.id = "msg-box"; // ID for the Box 
    this.createElements(this.id); 
    this.parentElement = parent; 
}; 
MessageBox.prototype = { 
    createElements: function(id){ 
     // Create Main Container 
     this.containerElement = document.createElement('div'); 
     this.containerElement.setAttribute('id', this.id); 
     this.parentElement.appendChild(this.containerElement); 
    } 
}; 

,但是當我把這個文件在我的index.html文件返回錯誤createElements()不是函數..

,這裏是我的index.html還有:

<script type="text/javascript"> 
     window.onload = function(){ 
      var box = MessageBox('body'); 
      //box.start(); 
     } 
    </script> 

回答

2

由於你的函數是一個構造函數,你要使用

var box = new MessageBox('body'); 
//  ^^^ 

否則,沒有創建實例,你的構造函數是默認的上下文對象上執行的,全球window對象(沒有createElements屬性)。看看MDN's introduction to the this keywordnew operator

+0

AAH,我犯了多麼愚蠢的錯誤。 –