JavaScript测试

JavaScript测试,javascript,testing,web,Javascript,Testing,Web,你能帮我吗 在一次测试中,我不理解这个问题: 给出以下代码,编写两行JavaScript来调用 print()函数的方式是在 JavaScript控制台 代码不能使用变量窗口。请随意评论 Printer = function(){ this.print = function() { console.log(this); } } var printer = new Printer(); 答复: printer.print.call(this); //or print

你能帮我吗

在一次测试中,我不理解这个问题:

给出以下代码,编写两行JavaScript来调用
print()
函数的方式是在 JavaScript控制台

代码不能使用变量
窗口
。请随意评论

Printer = function(){
    this.print = function() {
       console.log(this);
    }
}
var printer = new Printer();
答复:

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):


这就是教程想要告诉你的。希望对您有所帮助……

请更具体一些……您还不明白什么?我们不是读心术的人。现在是阅读全文并感谢您的回答的好时机,我不知道如何执行此操作:调用print()函数的方式可以在不使用变量窗口的情况下打印窗口全局对象。请尝试
printer.print.call(this)
非常感谢您的回答。请您解释一下这个代码好吗?在全局名称空间中(在浏览器中)
这个
窗口
…您可以自己查找
call()
 document.onclick=()=>{
 this.clicker++;
 };