[英]Javascript: When and when not to use "this"
我很好奇何時需要/最佳實踐使用關鍵字this
。 我知道this
是在確定this
值的函數時使用的,但它總是需要的嗎?
我問的原因是因為我有一個內部 function,它在我的模塊中被調用,它真正做的就是對你傳遞給它的一些數據進行排序。 我的問題是我應該使用this
關鍵字來調用這個 function 還是單獨調用。
例如:
function formatSomeData(data){
//code........
}
this.formatSomeData(data);
OR
formatSomeData(data);
我知道調用 function 的上下文及其目的在回答問題時很重要,但在這種情況下,就像我提到的那樣,我真的不需要在任何時候訪問this
object。 在調用函數時使用它仍然是好習慣嗎? 我要問的不是“這個”如何工作,而是什么時候適合使用它,什么時候不適合。
何時需要/最佳實踐使用關鍵字 this
這通常用於當您想訪問某些內容時。 因此,例如,如果您有一個自定義對象並想在某個方法中使用某些屬性,則應該使用this
。
function Person(fname, lname){ this.fname = fname; this.lname = lname; this.fullName = function(){ return this.fname + ' ' + this.lname; } } var p = new Person('foo', 'bar'); console.log(p.fullName())
如果你看到,在當前的構造函數中,我創建了一個函數( fullName
),它需要訪問它所屬對象的fname
和lname
屬性。 這是一個地方this
必須使用。
現在 while 聲明,什么時候使用
this
?
作為this
一部分的構造函數中的任何屬性都將是對象的一部分。 因此,如果您需要一些只能由您訪問但不能在外部訪問的東西,您可以使用function
而不是this
。
function Person(fname, lname){ var self = this; self.fname = fname; self.lname = lname; // This function is private function getFullName() { var name = ''; var seperator = ''; if (fname) { name += self.fname; seperator = ' '; } if (lname) { name += seperator + self.lname; } return name; } this.fullName = function(){ return getFullName(); } } var p = new Person('foo', 'bar'); console.log(p.fullName())
至於你的代碼,我已經在評論中解釋了它為什么起作用:
在非嚴格模式下,
this
將指向window
並且任何不在函數中的聲明都將成為全局范圍的一部分。
但正如@ Jonas W 的正確指針一樣,這是一種不好的做法。 為什么不好?
var|let|const
)定義的變量都將成為全局作用域的一部分。對於初級 JS 開發人員來說,通過在事件偵聽器回調中使用它來獲得 This 的概念可能是最容易的。 即,“click”事件將 this 綁定到作為目標的對象(比如“看,我點擊了這個!”)。
<ul class="dynamic-list" id="myList">
<li class="dynamic-list__item">Item 1</li>
<li class="dynamic-list__item">Item 2</li>
<li class="dynamic-list__item">Item 3</li>
</ul>
<script type="text/javascript">
let listItems = document.getElementById("myList").childNodes;
[...listItems].forEach(function(item) {
item.addEventListener("click", removeListItem, false);
})
// Callback for event, using THIS
function removeListItem() {
// Log the text content of <li> to the console. Which one? THIS one.
console.log(this.textContent);
// Get the parent of what? Of THIS! And remove its child. Which one? THIS one!
this.parentNode.removeChild(this);
}
</script>
當然,Rajeshs 的回答要復雜得多,但我希望這也能有所幫助……
編程是一種表達事物的方式,以便計算機和人類能夠理解它們。
在調用函數時使用它仍然是一個好習慣嗎?
沒有確切的答案。 你的兩個片段都有效。 所以計算機能夠理解它。 然而,第二個可能會讓人類(也就是你的同事)感到困惑:
this.someFunc();
我應該this
是指什么? 是的,從技術上講,它指的是window
,但從人類的角度來看,尚不清楚。 這就是為什么我會確定不是指this
在這種情況下。 但是,它還有其他很好的用例:
function changeColor(){
//When just looking here it makes no sense to refer to this
this.color = "green";
}
const car = { color: "grey" };
//But now it makes sense as `this` refers to the `car` it is called on
car.changeColor = changeColor;
TLDR:使用this
來引用方法/屬性,並在引用純函數和變量時將其保留。
讓我幫你處理這段代碼!
let emp_detail={
fname:"jemish",
lname:"italiya",
detailStatement:function() {
return this.fname+" "+this.lname;
}
}
讓我再舉一個例子
function Data(){
return this.result
}
var a=Data.bind({result:"I am the result!"})();
console.log(a) //I am the result!
'this' 在函數內部使用,它包含調用該函數的對象的值。
例如:
function a(){
this.newVariable = 'Phil';
}
a();
console.log(newVariable); //This line would display Phil
在這種情況下,即使我們只是在函數 a() 中定義了 newVariable。 調用該函數的對象是全局對象 window,因此 'this' 指向 window,而 this.newVariable 位於全局范圍內。
另一個例子是:
var c={
log:function(){
this.name = 'Phil';
}
}
在這種情況下,'this' 指向對象 c,因為日志函數將由 c 調用。
在 Javascript 中使用對象“this”時,我們有更多棘手的情況。 這是一篇掌握概念的好文章: http : //javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.