Bạn có thể tạo một hàm nhận một số đối số thay đổi:
function setAttributes(elem ) {
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%");
Hoặc, bạn chuyển các cặp thuộc tính / giá trị vào một đối tượng:
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%"
});
Bạn cũng có thể tạo phương thức / trình bao bọc đối tượng có thể điều khiển của riêng mình:
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%");
Ví dụ làm việc: http://jsfiddle.net/jfriend00/qncEz/
Object.assign()đáng xem xét cho những người không muốn tạo hàm trợ giúp - hoạt động cho "tất cả các thuộc tính có thể liệt kê và riêng ".