[英]Are there any good underscore.js alternatives that extend the core js classes?
[英]Underscore.js core
我正在瀏覽下划線庫的代碼,以了解其構建方式:
http://underscorejs.org/underscore.js
我了解其中的大部分內容,其中包含注釋,但是有些部分我還不了解:
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
為了了解其工作原理,我對其進行了一些更改:
function _(obj) {
if (obj instanceof _) {
return obj;
}
if (!(this instanceof _)) {
return new _(obj);
}
this._wrapped = obj;
}
// just an example, if statement to check if array
// is really an array should be added
_.sum = function (array) {
var sum = 0;
for (var i = 0, ilen = array.length; i < ilen; i += 1) {
sum += array[i];
}
return sum;
}
_.sum([1, 2, 3, 4, 5]); // 15
好的,現在我將使用_構造函數創建一個新實例。 即使我不提供新關鍵字,也可以使用,一切正常。
var _a = _([1, 2, 3, 4, 5]); // { _wrapped: [1, 2, 3, 4, 5] }
下一行的目的是什么?
if (obj instanceof _) return obj;
我可以刪除它,並且代碼仍然可以正常工作。 它僅用於處理以下情況嗎?
var _b = _(_a);
是的,它用於處理“已包裝”案件。
如果將下划線實例傳遞給_
它將返回該實例,而不是包裝它。 那是目的:
if (obj instanceof _) return obj;
作為證明- 這里是解決此問題的錯誤 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.