gpt4 book ai didi

javascript - 为什么这个 JavaScript 函数会产生这样的输出?

转载 作者:行者123 更新时间:2023-12-03 01:49:10 25 4
gpt4 key购买 nike

我有这个 JavaScript 代码:

var MyObject1 = function (a, b) {
return {
myA : a,
myB : b,
hello : function () { return "Hello !"; }
} ;
} ;

...和 ​​obj1 = MyObject1(1, 2) 将导致 obj1 设置为 {myA: 1, myB: 2, hello: ƒ},但我不明白为什么它会产生这个值。

另外,为什么obj1.myA;仍然是值1?是因为 hello 是一个闭包吗?

最佳答案

I write

obj1 = MyObject1(1, 2) // {"myA" :1,"myB" :2}

Can someone explain me why?

因为 MyObject 是一个返回对象的函数,因此如果您调用它,它会返回一个对象:)

when I write:

 obj1.myA; 

why does the answer remain 1, it is because hello is a closure?

因为您创建了一个新对象,并且该对象有一个属性myA,该属性在构造过程中设置为1。然后,您将该新对象分配给全局变量 obj1,以便您可以随时访问它。仅当您在另一个函数中使用一个函数时才涉及闭包,例如,如果您这样做:

 var MyObject1 = function (a, b) {
return {
myA : a,
myB : b,
hello : function () { return a; }
} ;
} ;

然后 ahello 内关闭,所以你可以这样做:

MyObject1(1,2).hello() // 1

关于javascript - 为什么这个 JavaScript 函数会产生这样的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50493579/

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