가변 개수의 인수를받는 함수를 만들 수 있습니다.
function setAttributes(elem /* attribute, value pairs go here */) {
for (var i = 1; i < arguments.length; i+=2) {
elem.setAttribute(arguments[i], arguments[i+1]);
}
}
setAttributes(elem,
"src", "http://example.com/something.jpeg",
"height", "100%",
"width", "100%");
또는 객체에 속성 / 값 쌍을 전달합니다.
function setAttributes(elem, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
elem[prop] = obj[prop];
}
}
}
setAttributes(elem, {
src: "http://example.com/something.jpeg",
height: "100%",
width: "100%"
});
자신 만의 체인 가능한 개체 래퍼 / 메서드를 만들 수도 있습니다.
function $$(elem) {
return(new $$.init(elem));
}
$$.init = function(elem) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
this.elem = elem;
}
$$.init.prototype = {
set: function(prop, value) {
this.elem[prop] = value;
return(this);
}
};
$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");
작동 예 : http://jsfiddle.net/jfriend00/qncEz/
Object.assign()도우미 함수를 만들고 싶지 않은 사람들을 찾아 볼 가치가 있습니다. "모든 열거 가능 하고 고유 한 속성"에 대해 작동합니다 .