Javascript 有人能解释一下这条线在干什么吗
有人能帮我了解一下这个函数的运行情况吗Javascript 有人能解释一下这条线在干什么吗,javascript,reactjs,Javascript,Reactjs,有人能帮我了解一下这个函数的运行情况吗 function getContainer(container, defaultContainer) { //this line below container = typeof container === 'function' ? container() : container; return ReactDOM.findDOMNode(container) || defaultContainer; } 正在为容器分配type
function getContainer(container, defaultContainer) {
//this line below
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container) || defaultContainer;
}
正在为容器分配typeof容器的结果,但如果容器等于一个函数,则调用该函数
我有点头疼。此代码取自反应组件模式的物料ui文档,其内容如下:
如果
容器
是一个函数,将其分配给名为容器
的变量,并将调用该函数,否则
将变量容器
设置为传递给getContainer
函数的参数容器
你也可以这样写,也许更容易阅读:
if (typeof container === 'function') {
container = container();
} else {
container = container;
}
在您的示例中,它使用三元运算符,这是编写
if
/else
语句的另一种方式。您可以阅读更多内容。它是这样说的:
如果
容器
是一个函数,将其分配给名为容器
的变量,并将调用该函数,否则
将变量容器
设置为传递给getContainer
函数的参数容器
你也可以这样写,也许更容易阅读:
if (typeof container === 'function') {
container = container();
} else {
container = container;
}
在您的示例中,它使用三元运算符,这是编写if
/else
语句的另一种方式。您可以阅读更多内容。相等的内容是:
if(typeof container === 'function')container= container();
else container = container;
它调用容器(如果它是函数)并将结果存储在名为container的变量中。它不是,它什么也不做。相等的是:
if(typeof container === 'function')container= container();
else container = container;
它调用容器(如果它是函数)并将结果存储在名为container的变量中。它不是什么都不做。首先,了解基本知识,了解我们引用js中函数/方法的方式的差异 假设有一个名为container的函数
function container() {
let name = 'Js';
return name;
}
console.log(container()); //js as we got the value here
console.log(typeof(container())) // string as this time we have value which of string type
console.log(typeof(container)) // function as we are pointig to function
当我们只引用函数名而不引用()
知道什么是
所以在你的问题中,它检查通过了什么,最后要知道的是
condition ? expr1 : expr2
i、 e首先,了解js中函数/方法的基本知识和不同之处 假设有一个名为container的函数
function container() {
let name = 'Js';
return name;
}
console.log(container()); //js as we got the value here
console.log(typeof(container())) // string as this time we have value which of string type
console.log(typeof(container)) // function as we are pointig to function
当我们只引用函数名而不引用()
知道什么是
所以在你的问题中,它检查通过了什么,最后要知道的是
condition ? expr1 : expr2
i、 e您应该查找三元运算符,这就是
a?b:c
construct被调用(在许多编程语言中,不仅仅是Javascript),你应该查找三元运算符,这就是a?b:c
construct被称为(在许多编程语言中,而不仅仅是Javascript)感谢老兄,typeof完全抛弃了我,我没有意识到我在看一个三元结构operator@juicy89就为了给我两分钱,你不应该这么做。函数参数应该只是一个数据类型,并且应该按照预期的方式使用它。调用具有不同数据类型的函数通常是一种糟糕的代码实践Hanks man,typeof完全抛弃了我,我没有意识到我在看一个三元函数operator@juicy89就为了给我两分钱,你不应该这么做。函数参数应该只是一个数据类型,并且应该按照预期的方式使用它。调用具有不同数据类型的函数通常是一种糟糕的代码实践