查看jQuery原始碼可以發現,jQuery中沒有使用new運算子來創建新物件,而是采用呼叫jQuery原型中init()函式的方式回傳一個新物件,
熟悉jQuery的人應該知道,幾乎jQuery所有操作,都是從$符號開始,當作為元素選擇器的時候,操作結果回傳的是一個jQuery物件,以下是個人模擬的寫法:
//模擬jQuery選擇器功能
(function () {
function jQuery(selector) {
return new jQuery.prototype.init(selector);
}
//init是存在jQuery原型上的一個方法
jQuery.prototype.init = function (selector) {
//選取dom原生的js
this.length = 0;
if (selector == null) {
return this;
}
if (typeof selector == 'string' && selector.indexOf('.') != -1) {
var dom = document.getElementsByClassName(selector.slice(1));
} else if (typeof selector == 'string' && selector.indexOf("#") != -1) {
var dom = document.getElementById(selector.slice(1));
}
if (selector instanceof HTMLElement || dom.length == undefined) {
this[0] = dom || selector;
this.length++;
} else {
for (var i = 0; i < dom.length; i++) {
this[i] = dom[i];
this.length++;
}
}
}
jQuery.prototype.css = function (propertyname, value) {
for (var i = 0; i < this.length; i++) {
//判斷傳入的值如果為物件
if (Object.prototype.toString.call(propertyname) == '[object Object]') {
//新陣列存盤物件的鍵和值
var arr = []
//遍歷物件鍵和值存入新陣列
for (key in propertyname) {
// console.log(i);
arr.push(key)
arr.push(propertyname[key])
}
//遍歷陣列給目標改變樣式
for (var j = 0; j < arr.length; j++) {
this[i].style[arr[j]] = arr[j + 1];
}
}
//判斷傳入的值是兩個值,設定css屬性
if (arguments.length == 2) {
this[i].style[arguments[0]] = arguments[1]
}
//判斷傳入的值是一個值表示回傳 CSS 屬性
if (arguments.length == 1) {
return window.getComputedStyle(this[i]).getPropertyValue(arguments[0])
// return window.getComputedStyle(this[i]).arguments[ 0];
}
}
return this;
}
//get實作
jQuery.prototype.get = function (num) {
//引數為空
if (num == null) {
//回傳一個真陣列
return [].slice.call(this, 0)
} else {
if (num >= 0) {
return this[num];
} else {
return this[this.length + num]
}
}
}
//eq實作
jQuery.prototype.eq = function (num) {
var dom = num != null ? (num >= 0 ? this[num] : this[num + this.length]) : null
return jQuery(dom)
}
//add實作
jQuery.prototype.add = function (adddom) {
if (adddom instanceof HTMLElement) {
this[this.length] = adddom;
this.length++;
return this;
}
if (typeof adddom == 'string') {
var arr = adddom.split(',')
for (var j = 0; j < arr.length; j++) {
this[this.length] = jQuery(arr[j])[0];
this.length++;
}
return this;
}
if (adddom.__proto__.constructor instanceof Object) {
this[this.length] = adddom[0];
this.length++;
return this;
}
}
//end實作
jQuery.prototype.end = function () {
this[this.length] = this[0].parentNode
this.length++;
return jQuery(this[this.length - 1]);
}
//init物件的原型指向jQuery原型
jQuery.prototype.init.prototype = jQuery.prototype
window.$ = window.jQuery = jQuery;
})()
本文首發于前端黑洞網,博客園同步跟新
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/273174.html
標籤:JavaScript
