2
재미 있기 때문에 jQuery의 구문/기능을 모방 할 수 있는지 확인하기로했습니다. 이것은 (브라우저 간/레거시 호환성에 대해 걱정하지 않을 때) 매우 쉬운 것으로 나타났습니다. 지금까지 내가 한 일을 여기에서 볼 수 있습니다 : http://jsfiddle.net/FPAaM/3/노드 프로토 타입 수정에 대한 우려 사항
이제 제 3 자 자바 스크립트 라이브러리의 발목을 밟지 않으려면 Node
의 프로토 타입에 기능을 추가 할 때주의해야 할 점과 NodeList
?
Node.prototype.text = function(txt){
var chld = this.childNodes;
while(chld[0]) this.removeChild(chld[0]);
this.appendChild(document.createTextNode(txt));
return this;
};
NodeList.prototype.text = function(txt){
for (var i = 0; i < this.length; i++)
this[i].text(txt);
return this;
};
Node.prototype.css = function(tag, val){
if (val != undefined)
this.style[tag] = val;
else
return this.style[tag];
return this;
};
NodeList.prototype.css = function(tag, val){
for (var i = 0; i < this.length; i++)
this[i].css(tag, val);
return this;
};
Node.prototype.clk = function(cbk){
this.addEventListener("click", cbk, false);
return this;
};
NodeList.prototype.clk = function(cbk){
for (var i = 0; i < this.length; i++)
this[i].clk(cbk);
return this;
};
var $ = function(args){
if (typeof args == "function")
document.addEventListener("DOMContentLoaded", args, false);
if (typeof args == "string")
return document.querySelectorAll(args);
return args;
};
$(function(){
$("div.fancy").text("Poor man's jQuery!")
.css("color", "red")
.clk(function(e){
if (this.css("color") == "red")
$(this).css("color", "green");
else
this.css("color", "red");
});
});
이상적으로는 모든 기본 객체의 프로토 타입을 연장하지 않습니다. jQuery는 그렇지 않습니다. –
@MichaelMior 왜? – Shmiddty
다른 라이브러리도이를 기대할 수 없으며 코드와 충돌하는 방식으로이를 수행 할 수 있습니다. 물론 많은 도서관은이 철학에 동의하지 않고 [Prototype] (http://prototypejs.org/)이 분명한 예입니다. –