이전에 '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/
? 어쩌면 그 뒤에 뭔가를 추가 할 수 있을까요? 그냥 추측 – Anonymous
'return this'는'magic(). do(). stuff() '에서처럼 체인을 가능하게합니다. –
예, 체인을 의미하는 것은 jquery와 비슷하지만 jquery는 좀 더 복잡하고 많은 객체를 반환합니다. – Anonymous