gpt4 book ai didi

javascript - "variable : function(){}"是什么意思?

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:01 25 4
gpt4 key购买 nike

在 Node.JS 示例代码中,我发现了如下代码块。

var messageReceivedCallBack = {
onMessageReceived: function (message) {
console.log('Message received ' + message);
}
};

这段代码是什么意思?具体来说,我无法理解带有冒号(':')的部分

最佳答案

这是一个对象字面量。这不是一个变量,它是一个属性名称:

var foo = {
a: 1,
b: 2
};

等同于:

var foo = {};
foo.a = 1;
foo.b = 2;

同样:

var foo = {
a: function () {}
};

等同于:

var foo = {};
foo.a = function () {};

因此如下:

var messageReceivedCallBack = {
onMessageReceived: function (message) {
console.log('Message received ' + message);
}
};

只是这样做:

var messageReceivedCallBack = {};

messageReceivedCallBack.onMessageReceived = function (message) {
console.log('Message received ' + message);
};

关于javascript - "variable : function(){}"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38783036/

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