gpt4 book ai didi

javascript - ._ 在 javascript 中是什么?

转载 作者:行者123 更新时间:2023-11-30 11:06:45 24 4
gpt4 key购买 nike

我在浏览下划线 js 源代码时遇到过这个问题。

var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this ||
{};

// Save the previous value of the `_` variable.
var previousUnderscore = root._;

root._ 在这里做什么?

最佳答案

一般,该代码块将导致 previousUnderscore 引用 self 上的 _ 属性,或在 global 上,或在 this 上(无论 root 评估到哪个对象),并且所述属性值可能不存在。它与任何其他属性名称没有区别。

例如,如果第一个条件通过:

typeof self == 'object' && self.self === self && self

然后如果 self 有一个包含 'foo'_ 属性,那么 previousUnderscore 将被分配给它相同的字符串,'foo'

const self = {
_: 'foo'
};
self.self = self;

var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this ||
{};

// Save the previous value of the `_` variable.
var previousUnderscore = root._;
console.log(previousUnderscore, typeof previousUnderscore);

如果 self 没有 _ 属性,那么 previousUnderscore 将是 undefined

完全相同的逻辑适用于任何其他属性名称,例如:

const self = {
somePropName: 'foo'
};
self.self = self;

var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this ||
{};

// Save the previous value of the `_` variable.
var previousUnderscore = root.somePropName;
console.log(previousUnderscore, typeof previousUnderscore);

特别,对于underscore.js来说,这段代码是干什么的

(1) 确定哪个对象应该用于root变量名

(2) 将该对象中的_ 属性保存在变量名previousUnderscore 中,这样当underscore.js 重新分配root._ 时, 然后可以调用 noConflict

Give control of the _ variable back to its previous owner

通过运行以下行:

root._ = previousUnderscore;

例如,如果你运行 underscore.js 并且之前在全局对象(比如 Lodash)上有 _,那么 _ 会引用 Underscore 对象——但是如果你调用了 noConflict,那么 _ 会引用它最初引用的任何东西(比如 Lodash)。

// Underscore runs after Lodash, so when the JS here runs initially,
// _ refers to Underscore, but Underscore has saved a reference to the previous _,
// which was Lodash,
// in the variable name previousUnderscore that your question is asking about:


// Underscore function - give _ back to Lodash:
_.noConflict();
// Lodash function:
_.noop()

console.log('done');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

关于javascript - ._ 在 javascript 中是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55292906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com