Bạn trên dẫn link API chi tiết rồi mà bạn không hiểu, thì mình chuyển sang đọc source code cho tiện. 
Hàm toType(obj)
có thể xem là kết quả của typeof obj
. Với obj là string thì toType(obj)
trả về chuỗi “string”
function toType(obj) {
if (obj == null)
return obj + '';
return (
typeof obj === 'object' ||
typeof obj === 'function' ?
class2type[toString.call(obj)] || "object" :
typeof obj;
);
}
Hàm isFunction()
kiểm tra 1 object có phải là function. Nghĩ đơn giản vậy là được rồi.
var isFunction = function isFunction(obj) {
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
Code sau khi đơn giản thế này, trích từ code gốc của jQuery. Mình loại mấy trường hợp tính toán và gọi hàm linh tinh thì rút gọn được vậy.
jQuery.fn.extend({
attr: function (name, value) {
if (toType(name) === 'object') {
// do other stuff
}
if (!isFunction(value)) {
// another stuff
}
for (var i = 0; i < this.length; i++) {
var elem = this[i];
if (typeof elem.getAttribute === 'undefined') {
jQuery.fn.prop.call(elem, name, value);
break;
}
var originValue = elem.getAttribute(name);
var newValue = value.call(elem, i, originValue);
elem.setAttribute(name, newValue);
}
}
});
Trong jQuery.fn.extend
có nhận object, object có property là attr
kiểu function object
. Khi gọi $('#w3s').attr()
thì gọi tới function
của attr
.
-
this
là $('#w3s')
-
name
là href
, kiểu string
-
value
là function () {...}
Trình tự như sau:
-
toType('href')
trả về “string”, block trong if không thực hiện.
-
value
là function object, isFunction(value)
trả về true, block trong if không thực hiện.
-
this
là kết quả sau khi thực thi $('w3s')
, kiểu array-like object, có property length
và các property có property descriptor Enumerable là true, dạng “0”, “1”, “2”
-
Dùng for
để lấy từng phần tử trong array-like object this
, gán vào elem
.
-
Kiểm tra elem
có property getAttribute
hay không, nếu không sử dụng jQuery function prop thay thế. Giả sử elem
có getAttribute
, typeof elem.getAttribute === 'undefined'
trả về false. Block trong if không thực hiện.
-
Lấy giá trị attribute ‘href’ thông qua getAttribute
, gán vào biến originValue
.
-
value
là function object, gọi value()
với các tham số i
là index của for
, originValue
là giá trị vừa lấy, giá trị trả về gán vào newValue
(Trả lời câu hỏi ban đầu của thớt luôn, i
và originValue
gọi ở đâu?)
-
Gán giá trị mới newValue
vào ‘href’ của elem
.