[英]Why is this function logging undefined (JavaScript closure)
想知道為什么init函數最終會記錄未定義的日志,因為在調用logStartDate之前已定義了startDate。
編碼:
var startDate;
var init = function(startDate) {
this.startDate = startDate;
logStartDate();
};
var logStartDate = function() {
console.log(startDate);
};
init('2015-01-02');
機會是你的代碼不起作用,因為價值this
是不是你希望它是如此如此什么this.startDate
不會改變變量startDate
你在你的代碼,因此該變量從未初始化。
您在該參考文獻中濫用了this
,因此這是開始修復代碼的地方。 實際上,如果您以strict
模式運行代碼,則代碼將生成錯誤,因為this
將是undefined
。 strict
設計了strict
模式,以防止不良的編碼做法,例如不小心以錯誤的方式使用this
。
為什么
this.startDate
結構不好,什么是更好的結構?
this
用於在obj.method()
中obj.method()
方法調用中的對象。 里面的method
, this
將涉及到obj
或this
可以在其他一些情況下使用時,函數的調用者明確導致的價值this
被設置為一個有意義的值。 在普通函數調用中, this
將是全局對象,或者在嚴格模式下將是undefined
,通常不應使用。 見這個答案對的價值到底是什么情況的列表this
設置為獨特的東西。
在正常的函數調用中,調用者未明確為您設置this
功能,因此您根本不應使用this
。 實際上,如果您以嚴格模式運行代碼(強烈建議使用this
模式),則init
函數中undefined
其值。
如果您只是試圖將名為startDate
高級范圍變量設置為傳遞給init
的值,則應將init
函數的參數名稱更改為一個無沖突的名稱,然后直接引用startDate
像這樣的變量:
var startDate;
var init = function(initialDate) {
startDate = initialDate;
logStartDate();
};
var logStartDate = function() {
console.log(startDate);
};
init('2015-01-02');
函數表達式不是閉包嗎?
僅在某些情況下,當函數內部的某種內部引用持續存在時,才可以創建閉包,從而在函數執行完后使函數的作用域保持活動狀態。 所有函數表達式都不是閉包。 您沒有在此代碼中關閉。 請參閱JavaScript閉包如何工作? 有關閉包的更多討論。
因為在init
內部,所以要設置this.Startdate
( init
的私有成員var)的值。
您需要修改以使用window
范圍:
var startDate;
var init = function(date) {
startDate = date;
logStartDate();
};
var logStartDate = function() {
console.log(startDate);
};
init('2015-01-02');
因為startDate 2
等於startDate 1
,而不是其他startDate 。
var startDate; // 1 var init = function(startDate) { // startDate here is '2015-01-02' this.startDate = startDate; // not equal to startDate line 1 logStartDate(); }; var logStartDate = function() { console.log(startDate); // 2, equal to startDate line 1 }; init('2015-01-02');
改用這個:
var startDate; var init = function(date) { startDate = date; logStartDate(); }; var logStartDate = function() { console.log(startDate); }; init('2015-01-02');
您這里遇到的問題是logStartDate試圖console.log您定義的第一個startDate變量,但是沒有為其賦值,因此它返回的是“ undefined”。 變量名稱選擇不當也部分導致了這種混亂。
var startDate; //you defined a new variable startDate
var init = function(date) { //you defined init, and passed a parameter called date (renamed for clarity)
this.startDate = date; //you set this.startDate to the date parameter
logStartDate(); //you call logStartDate() but have not passed this.startDate as an argument,
};
var logStartDate = function() {
console.log(startDate); // you are console logging the original startDate variable defined at the top of the code block, which did not get assigned a value
};
init('2015-01-02');
更好的實現將是這樣的
var init = function(date) {
logStartDate(date);
};
var logStartDate = function(date) {
console.log(date);
};
init('2015-01-02');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.