2016-12-25 68 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