我剛纔在閱讀如何'創建一個JavaScript庫',我遇到了這些代碼,讓我想把我的頭髮撕掉。這些代碼片段如何工作?
這裏是得到了我的大腦在海里代碼:
if (window === this) {
return new _(id);
}
_(ID)就是在此代碼包含函數名。如果你需要自己查看它,下面是其餘的代碼。
function _(id) {
// About object is returned if there is no 'id' parameter
var about = {
Version: 0.5,
Author: "Michael Jasper",
Created: "Fall 2010",
Updated: "23 November 2011"
};
if (id) {
// Avoid clobbering the window scope:
// return a new _ object if we're in the wrong scope
if (window === this) {
return new _(id);
}
// We're in the correct object scope:
// Init our element object and return the object
this.e = document.getElementById(id);
return this;
} else {
// No 'id' parameter was given, return the 'about' object
return about;
}
};
我從來沒有見過'返回新功能',但我很想了解它的功能。
另一段代碼:
_.prototype = {
hide: function() {
this.e.style.display = 'none';
return this;
}
show: function() {
this.e.style.display = 'inherit';
return this;
}
};
我知道這個代碼添加新的方法到_對象,但爲什麼他們「返回這個」?我試過沒有,它工作得很好。
最後一兩件事,鏈接到文章http://www.mikedoesweb.com/2012/creating-your-own-javascript-library/
Return this?那麼也許你可以在它後面追加更多的東西?只是猜測 – Anonymous
'return this'啓用鏈接,如'magic()。do()。stuff()'。 –
是的,鏈接是我的意思,它就像jquery,但jquery有點複雜,並返回許多對象 – Anonymous