2016-05-19 42 views
0

我有測試運行的業力,在其中一個我創建對象的new instance並呼籲function其中使用this。在正常的瀏覽器this是參考當前的實例,但在測試console.log後,我看到:測試新的對象實例(茉莉花)

對象{文件:< - 這是執行上下文。

在iframe中加載。每次執行運行前重新加載。

爲什麼?

// createing the object 
 

 
window.gr = window.gr || {}; 
 

 
gr.Notification = (function() { 
 
    function Notification(node, message) { 
 
     this.liveTime = 5000; 
 
     this.template = this.createTemplate(message); 
 
     this.node = null; 
 
     this.appendTo(node); 
 

 
     setTimeout(this.remove, this.liveTime); 
 
    } 
 

 
    Notification.prototype = { 
 
     createTemplate: function (message) { 
 
      var notification = document.createElement("div"); 
 
      notification.className = "notification"; 
 

 
      var _message = document.createTextNode(message); 
 
      notification.appendChild(_message); 
 

 
      return notification; 
 
     }, 
 
     appendTo: function(node){ 
 
      this.node = node.appendChild(this.template); 
 
     }, 
 
     remove: function(){ 
 
      console.log(this) 
 
      this.node.parentNode.removeChild(this.node); 
 
     } 
 
    }; 
 

 
    return Notification; 
 
})(); 
 

 

 
//test 
 

 
beforeEach(function(){ 
 
     Notification = gr.Notification; 
 
     jasmine.clock().install(); 
 
    }); 
 

 
it("should remove notification after 5s", function(){ 
 
     new Notification(document.body); 
 

 
     jasmine.clock().tick(5001); 
 

 
     expect(document.querySelectorAll(NOTIFICATION_SELECTOR).length).toEqual(0); 
 
    });

+0

如果您可以包含實際的代碼而不是摘要,那將會非常有幫助。確切的行爲可能會根據您調用對象的方式和位置而改變。 – ssube

+0

在沒有上下文的情況下很難形象化發生的事情,但是,Jasmine在每個「it」之後清理body DOM內容,嘗試在beforeEach中創建這個新實例嗎? –

+0

我編輯帖子並添加代碼 – Alcadur

回答

0

this引用window,因爲你調用setTimeout的,這是一個方法點內window對象的方法,所以thiswindow

你可以做這樣的事情:

function Notification(node, message) { 
     this.liveTime = 5000; 
     this.template = this.createTemplate(message); 
     this.node = null; 
     this.appendTo(node); 

     var self = this; 

     setTimeout(function() { 
      self.remove() 
     }, self.liveTime); 

    }