Javascript Vanilla JS |也包含属性的可调用对象

Javascript Vanilla JS |也包含属性的可调用对象,javascript,json,Javascript,Json,在一些作业中,我被要求做以下工作: fun4():返回可以作为函数调用的对象。这个对象还应该有一个空值的“k”属性(所以fun4()()应该做些什么) 问题的第一部分简单易懂。 第二个是我的问题。 如何在JS中创建可以静态调用和访问的对象 要简化: 可以创建一个行为如下的对象: > let o = CustomObject; > o.k < null > o() < //Some value returned here from the function >设o=

在一些作业中,我被要求做以下工作:

fun4():返回可以作为函数调用的对象。这个对象还应该有一个空值的“k”属性(所以fun4()()应该做些什么)

问题的第一部分简单易懂。 第二个是我的问题。 如何在JS中创建可以静态调用和访问的对象

要简化: 可以创建一个行为如下的对象:

> let o = CustomObject;
> o.k
< null
> o()
< //Some value returned here from the function
>设o=CustomObject;
>好的
o()

谢谢

我觉得这很简单

let CustomObject = function(){ return "hello"; }
CustomObject.k = null;

这将通过您的验收标准

我觉得很简单

let CustomObject = function(){ return "hello"; }
CustomObject.k = null;

这将通过您的验收标准

至于vanilla js,这就是您要寻找的:

var fun4 = function () {
    let val = function () { console.log("hello"); };
    val.k = null;

    return val;
}


fun4()   // returns the function
fun4()() // logs 'hello'
fun4().k // returns null
鉴于上面的一条评论,需要注意的一件事是使用
let
var
。在这种情况下,可以使用
var
,没有任何区别(当函数返回时
val
超出范围时,将释放变量进行垃圾收集)。但是,当您在控制台中运行此操作时(而不是在函数或其他定义良好且隔离的作用域中),使用
let
创建的变量将在每次调用后销毁——换句话说,只要您按return键。证明这一点的方法是比较以下各项:

var test = function () {
    let x = 1;
    let x = 1;  // this will cause an immediate syntax error when the script is parsed;
}
另一方面:

> let x = 1;
< undefined
> let x = 1; // In the console, this will not raise any error/exception
             // because the scope is cleared after the line above has
             // executed and returned
< undefined
>设x=1;
<未定义
>设x=1;//在控制台中,这不会引发任何错误/异常
//因为上面的行被删除后,范围被清除
//执行并返回
<未定义

至于vanilla js,这就是您想要的:

var fun4 = function () {
    let val = function () { console.log("hello"); };
    val.k = null;

    return val;
}


fun4()   // returns the function
fun4()() // logs 'hello'
fun4().k // returns null
鉴于上面的一条评论,需要注意的一件事是使用
let
var
。在这种情况下,可以使用
var
,没有任何区别(当函数返回时
val
超出范围时,将释放变量进行垃圾收集)。但是,当您在控制台中运行此操作时(而不是在函数或其他定义良好且隔离的作用域中),使用
let
创建的变量将在每次调用后销毁——换句话说,只要您按return键。证明这一点的方法是比较以下各项:

var test = function () {
    let x = 1;
    let x = 1;  // this will cause an immediate syntax error when the script is parsed;
}
另一方面:

> let x = 1;
< undefined
> let x = 1; // In the console, this will not raise any error/exception
             // because the scope is cleared after the line above has
             // executed and returned
< undefined
>设x=1;
<未定义
>设x=1;//在控制台中,这不会引发任何错误/异常
//因为上面的行被删除后,范围被清除
//执行并返回
<未定义

您可以看到一个“k”属性,如下所示


您可以看到一个“k”属性,如下所示


这很有效,我以前也写过类似的东西。问题是-如果我(通过Chrome)登录,为什么我看不到这个属性(但我可以访问它)@Olivarra1因为Chrome将其视为一个函数,并提供“函数”视图。尝试执行
console.log(“%O”,CustomObject)
,它将为您提供“object”视图。这段代码对于检查DOM元素也非常有用(
console.log(“%O”,element)
),这很有效,我以前也写过类似的东西。问题是-如果我(通过Chrome)登录,为什么我看不到这个属性(但我可以访问它)@Olivarra1因为Chrome将其视为一个函数,并提供“函数”视图。尝试执行
console.log(“%O”,CustomObject)
,它将为您提供“object”视图。此代码对于检查DOM元素也非常有用(
console.log(“%O”,element)
)感谢您的澄清:)感谢您的澄清:)