2016-05-19 36 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); 

    }