[英]JavaScript chaining functions, last methods returns 'undefined'
[英]Javascript Chaining return undefined
我有這個OOP作品的問題。 基本上,此$("notfound")
不在文檔中。 它放了一個錯誤。 但是如果將其更改為$("parent")
則可以正常運行,因為它在文檔中。
檢查這個小提琴:
https://jsfiddle.net/k6j70f1h/8/
在console.log中,子項未定義。
如何得到這個東西的作品?
我的代碼有什么問題?
"use strict" var $, i; (function() { $ = function(el, context) { context = context || document; return new obj$(el, context); }; var obj$ = function(el, context) { var cl = context.getElementsByClassName(el), loop = cl.length; this.length = loop; for (i = 0; i < loop; i++) { this[i] = cl[i]; } }; obj$.prototype = { find : function(el) { if (this.length == 1) { return $( el, this[0] ); } }, css : function(obj, data) { if (this.length == 1) { this[0].style[obj] = data; return this; } } }; })(); var parent = $("notfound"), // this one cause error child = parent.find("child"); // throw an error child is undefined child.css("color", "orange"); parent.css("color", "purple");
<div class="parent">parent <div class="child">child</div> </div>
您所說的導致錯誤的行沒有引起錯誤。
導致錯誤的行是:
child.css("color", "orange");
引起錯誤的原因是此行:
var parent = $("notfound"),
...返回length == 0
的parent
對象,因此此行:
child = parent.find("child"); // throw an error child is undefined
...電話find
一個對象,其中上this.length
不是1
,所以在代碼中find
不進入體內的的if
聲明,你不返回任何東西。 這意味着調用parent.find(...)
導致undefined
,您已將其分配給child
。 因此, child.css(...)
嘗試在undefined
上調用css
。
如果您想制作類似jQuery的內容,則需要添加
return $();
...查找parent.find
如果this.length
為0(至少):
find : function(el) {
if (this.length == 1) {
return $( el, this[0] );
}
return $();
}
同樣,如果您想模擬jQuery,則總是希望從css
函數return this
值,而不僅僅是具有一個元素。
這是具有最少必要更改的更新:
"use strict" var $, i; (function() { $ = function(el, context) { context = context || document; return new obj$(el, context); }; var obj$ = function(el, context) { var cl = context.getElementsByClassName(el), loop = cl.length; this.length = loop; for (i = 0; i < loop; i++) { this[i] = cl[i]; } }; obj$.prototype = { find : function(el) { if (this.length == 1) { return $( el, this[0] ); } return $(); // Added }, css : function(obj, data) { if (this.length == 1) { this[0].style[obj] = data; } return this; // Moved } }; })(); var parent = $("notfound"), // this one cause error child = parent.find("child"); // throw an error child is undefined child.css("color", "orange"); parent.css("color", "purple");
<div class="parent">parent <div class="child">child</div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.