var $p = $("p")
$p.css("font-size","40px") //css是原型方法
console.log($p.html()) //html是原型方法
var $div1 = $("#div1")
$div1.css("color","blue") //css是原型方法
console.log($div1.html()) //html是原型方法
zepto如何使用原型
//空對(duì)象
var zepto = {}
zepto.init = function(){
//源碼中,這里的處理情況比較復(fù)雜。但因?yàn)槭潜敬沃皇轻槍?duì)原型,因此這里就弱化了
var slice = Array.prototype.slice
var dom = slice.call(document.querySelectorAll(selector))
return zepto.Z(dom,selector)
}
//即使用zepto時(shí)候的$
var $ = function(selector){
return zepto.init(selector)
}
//這就是構(gòu)造函數(shù)
function Z(dom, selector) {
var i, len = dom ? dom.length : 0
for (i = 0; i < len; i++) {
this[i] = dom[i]
}
this.length = len
this.selector = selector || ""
}
zepto.Z = function(dom, selector) {
return new Z(dom, selector)
}
(function(window) {
var zepto = {};
function Z(dom, selector) {
var i, len = dom ? dom.length : 0;
for (i = 0; i < len; i++) {
this[i] = dom[i];
}
this.length = len;
this.selector = selector || "";
}
zepto.Z = function(dom, selector) {
return new Z(dom, selector);
}
zepto.init = function(selector) {
var slice = Array.prototype.slice;
var dom = slice.call(document.querySelectorAll(selector));
return zepto.Z(dom, selector);
}
var $ = function(selector) {
return zepto.init(selector);
}
window.$ = $;
$.fn = {
css: function(key, value) {
console.log(key, value);
},
html: function() {
return "html";
}
}
Z.prototype = $.fn
})(window)
jquery如何使用原型
var jQuery = function(selector){
//注意new關(guān)鍵字,第一步就找到了構(gòu)造函數(shù)
return new jQuery.fn.init(selector);
}
//定義構(gòu)造函數(shù)
var init = jQuery.fn.init = function(selector){
var slice = Array.prototype.slice;
var dom = slice.call(document.querySelectorAll(selector));
var i,len=dom?dom.length:0;
for(i = 0;i原型的擴(kuò)展性
function waitHandle(){
var dtd = $.Deferred(); //創(chuàng)建一個(gè)deferred對(duì)象
var wait = function(dtd){ // 要求傳入一個(gè)deferred對(duì)象
var task = function(){
console.log("執(zhí)行完成");
dtd.resolve(); //表示異步任務(wù)已完成
//dtd.reject() // 表示異步任務(wù)失敗或者出錯(cuò)
};
setTimeout(task,2000);
return dtd;
}
//注意,這里已經(jīng)要有返回值
return wait(dtd);
}
//使用
var w = waithandle()
w.then(function(){
console.log("ok1");
},function(){
console.log("err2");
})
.then(function(){
console.log("ok2");
},function(){
console.log("err2");
})
//還有w.wait w.fail
總結(jié):dtd的API可分成兩類(lèi),用意不同
第一類(lèi):dtd.resolve 、 dtd.reject
第二類(lèi):dtd.then、dtd.done、dtd.fail
這兩類(lèi)應(yīng)該分開(kāi),否則后果嚴(yán)重!
可以在上面代碼中最后執(zhí)行dtd.reject()試一下后果
使用dtd.promise()
function waitHandle(){
var dtd = $.Deferred();
var wait = function(){
var task = function(){
console.log("執(zhí)行完成");
dtd.resolve();
}
setTimeout(task,2000)
return dtd.promise(); //注意這里返回的是promise,而不是直接返回deferred對(duì)象
}
return wait(dtd)
}
var w = waitHandle(); //promise對(duì)象
$.when(w).then(function(){
console.log("ok1");
},function(){
console.log("err1");
})
//w.reject() //w.reject is not a function
var div = document.createElement("div");
var item,result = "";
for(item in div){
result += "|" + item;
}
console.log(result);
//瀏覽器默認(rèn)創(chuàng)建出來(lái)的DOM節(jié)點(diǎn),屬性是非常多的
//result
|align|title|lang|translate|dir|dataset|hidden|tabIndex|accessKey|draggable|spellcheck|autocapitalize|contentEditable|isContentEditable|inputMode|offsetParent|offsetTop|offsetLeft|offsetWidth|offsetHeight|style|innerText|outerText|onabort|onblur|oncancel|oncanplay|oncanplaythrough|onchange|onclick|onclose|oncontextmenu|oncuechange|ondblclick|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|ondurationchange|onemptied|onended|onerror|onfocus|oninput|oninvalid|onkeydown|onkeypress|onkeyup|onload|onloadeddata|onloadedmetadata|onloadstart|onmousedown|onmouseenter|onmouseleave|onmousemove|onmouseout|onmouseover|onmouseup|onmousewheel|onpause|onplay|onplaying|onprogress|onratechange|onreset|onresize|onscroll|onseeked|onseeking|onselect|onstalled|onsubmit|onsuspend|ontimeupdate|ontoggle|onvolumechange|onwaiting|onwheel|onauxclick|ongotpointercapture|onlostpointercapture|onpointerdown|onpointermove|onpointerup|onpointercancel|onpointerover|onpointerout|onpointerenter|onpointerleave|nonce|click|focus|blur|namespaceURI|prefix|localName|tagName|id|className|classList|slot|attributes|shadowRoot|assignedSlot|innerHTML|outerHTML|scrollTop|scrollLeft|scrollWidth|scrollHeight|clientTop|clientLeft|clientWidth|clientHeight|attributeStyleMap|onbeforecopy|onbeforecut|onbeforepaste|oncopy|oncut|onpaste|onsearch|onselectstart|previousElementSibling|nextElementSibling|children|firstElementChild|lastElementChild|childElementCount|onwebkitfullscreenchange|onwebkitfullscreenerror|setPointerCapture|releasePointerCapture|hasPointerCapture|hasAttributes|getAttributeNames|getAttribute|getAttributeNS|setAttribute|setAttributeNS|removeAttribute|removeAttributeNS|hasAttribute|hasAttributeNS|toggleAttribute|getAttributeNode|getAttributeNodeNS|setAttributeNode|setAttributeNodeNS|removeAttributeNode|closest|matches|webkitMatchesSelector|attachShadow|getElementsByTagName|getElementsByTagNameNS|getElementsByClassName|insertAdjacentElement|insertAdjacentText|insertAdjacentHTML|requestPointerLock|getClientRects|getBoundingClientRect|scrollIntoView|scrollIntoViewIfNeeded|animate|computedStyleMap|before|after|replaceWith|remove|prepend|append|querySelector|querySelectorAll|webkitRequestFullScreen|webkitRequestFullscreen|scroll|scrollTo|scrollBy|createShadowRoot|getDestinationInsertionPoints|ELEMENT_NODE|ATTRIBUTE_NODE|TEXT_NODE|CDATA_SECTION_NODE|ENTITY_REFERENCE_NODE|ENTITY_NODE|PROCESSING_INSTRUCTION_NODE|COMMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE|DOCUMENT_FRAGMENT_NODE|NOTATION_NODE|DOCUMENT_POSITION_DISCONNECTED|DOCUMENT_POSITION_PRECEDING|DOCUMENT_POSITION_FOLLOWING|DOCUMENT_POSITION_CONTAINS|DOCUMENT_POSITION_CONTAINED_BY|DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC|nodeType|nodeName|baseURI|isConnected|ownerDocument|parentNode|parentElement|childNodes|firstChild|lastChild|previousSibling|nextSibling|nodeValue|textContent|hasChildNodes|getRootNode|normalize|cloneNode|isEqualNode|isSameNode|compareDocumentPosition|contains|lookupPrefix|lookupNamespaceURI|isDefaultNamespace|insertBefore|appendChild|replaceChild|removeChild|addEventListener|removeEventListener|dispatchEvent
var container = document.getElementById("container")
var vnode = h("div#container.two.classes", { on: { click: someFn } }, [
h("span", { style: { fontWeight: "bold" }, "This is bold" }),
"and this is just normal text",
h("a", { props: { href: "/foo" } }, "I"ll take you places")
])
//patch into empty DOM element - this modifies the DOM as a side effect
patch(container, vnode)
var newVnode = h("div#container.two.classes", { on: { click: anotherEventHandle } }, [
h("span", { style: { fontWeight: "normal", fontStyle: "italic" } }, "this is now italic type"),
"and this is still just normal text",
h("a", { props: { href: "/bar" } }, "I"ll take you places")
])
//send `patch` invocation
patch(vnode, newVnode); //Snabbdom efficiently updates the old view to the new state
function createElement(vnode) {
var tag = vnode.tag;
var attrs = vnode.attrs || {};
var children = vnode.children || [];
if (!tag) {
return null
}
//創(chuàng)建元素
var elem = document.createElement(tag);
//屬性
var attrName;
for (attrName in atts) {
if (attrs.hasOwnProperty(attrName)) {
elem.setAttribute(attrName, attrs[attrName])
}
}
//子元素
children.array.forEach(childVnode => {
elem.appendChild(createElement(childVnode))
});
return elem;
}
//vm._l
function renderList(val,render) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === "string") {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === "number") {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
if (isDef(ret)) {
(ret)._isVList = true;
}
return ret
}
//分享
function invokeShare(data,callback){
_invoke("share",data,callback)
}
//登錄
function invokeLogin(data,callback){
_invoke("login",data,callback)
}
//打開(kāi)掃一掃
function invokeScan(data,callback){
_invoke("scan",data,callback)
}