[英]how to understand underscore before a statement in javascript
_
在此示例代码中是什么意思:
if (_(abc.content).has("abc")){
console.log("abc found");
}
许多人说“ _”表示私有成员,但是如果abc
或content
是私有成员,我们不应该使用_abc.content
或abc._content
吗?
谢谢
为了使它有效, _
必须引用一个函数 。 脚本可能使用underscore
,在这种情况下_(abc.content).has("abc")
返回一个布尔值-如果abc.content
对象的键为abc
,则返回true
否则返回false
:
const abc = { content: { key1: 'foo', abc: 'bar' } }; if (_(abc.content).has("abc")){ console.log("abc found"); } console.log(_(abc.content).has("keyThatDoesNotExist"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
它可能与私有属性无关,因为_
是一个独立的函数。
使用的库也可能是lodash:
const abc = { content: { key1: 'foo', abc: 'bar' } }; if (_(abc.content).has("abc")){ console.log("abc found"); } console.log(_(abc.content).has("keyThatDoesNotExist"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
但是可以肯定的是,您必须检查_
- console.log
或查看它的定义位置,以获得一些想法。
那只是一个变量名。 没错,约定建议下划线指代对象中的私有成员,例如:
const num = 2;
function Multiply(num) {
this._multiplier = 2;
this._input = num;
this.start = function(){
return this._multiplier * this._input;
}
}
const product = new Multiply(num).start(); //4
但是,私有成员的概念与您的示例无关。
就您而言, _()
实际上是一个函数;
function _ (){
return "I love potatoes";
}
一个函数,该函数返回包含.has()
方法的对象。 您的功能结构可以简化为
function _(args){
const content = args;
return {
has: function(data){
//do something
return true; //some boolean expression
}
}
}
_是JavaScript中的有效变量名,可以按照您想要的任何方式使用,就像i,a,x,长度,时间,日期或您可以想到的任何其他变量名一样。
就个人而言,当我不会在函数主体中使用该变量时,通常会在函数参数列表中使用下划线作为变量。
const func = (_) => {
// _ is not used in the function body
};
const _ = () => { console.log('Hello from underscore!'); }; _();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.