2016-12-25 48 views
-2

你能帮助我吗?JavaScript测试

在测试过程中,我不明白这个问题:

考虑下面的代码,编写JavaScript的两行调用 print()功能,打印在 的JavaScript窗口全局对象的方式安慰?您的代码不得使用变量window。随意发表评论。

Printer = function(){ 
    this.print = function() { 
     console.log(this); 
    } 
} 
var printer = new Printer(); 
+2

请更具体...你不明白什么?我们不介意读者。现在将是阅读[问]和[问题清单]的好时机(http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) – charlietfl

+0

谢谢你的回答,我不明白如何执行此操作:以不使用变量窗口的方式打印Window全局对象,调用print()函数。 – souf

+1

试试'printer.print.call(this)' – charlietfl

回答

1

答:

printer.print.call(this); 
//or 
printer.print.bind(this)(); 

为什么这是有用的:

例子:在一个对象添加一个事件侦听器:

function person(){ 
this.clicker=0; 
document.body.addEventListener("click",function(){ 
this.clicker++; 
}); 
} 

所以这应该工作,不应该它?不,它不会导致eventlistener自动将它作为单击元素绑定。所以这将是身体,这不是一个发声器属性。因此,在这种情况下它的有用覆盖此...

document.body.addEventListener("click",function(){ 
this.clicker++; 
}.bind(this)) 

或者在新的浏览器(见箭头funcs中):

document.onclick=()=>{ 
this.clicker++; 
}; 

那教程想告诉你什么。希望它有帮助...

+0

非常感谢@Jonas w,这很好 – souf