简体   繁体   English

为什么我们在JavaScript return语句中使用functionName:函数

[英]Why do we use functionName: function in javascript return statement

I am completely new to javascript. 我对javascript完全陌生。 I saw the below snippet in a tutorial. 我在教程中看到了以下片段。 But i am not sure why do we use funtionName: function in return statement. 但是我不确定为什么我们在return语句中使用funtionName:函数。

For example, getID:function() and setID: function() in the below code. 例如,以下代码中的getID:function()和setID:function()。 Can anybody explain. 谁能解释。

function celebrityID () {
    var celebrityID = 999;

    return {
        getID: function ()  {

          return celebrityID;
        },
        setID: function (theNewID)  {

            celebrityID = theNewID;
        }
    }

}

in your celebrityID () function you are returning an object, which has two properties those properties are function. celebrityID ()函数中,您将返回一个对象,该对象具有两个属性,这些属性是函数。

you can call 你可以打电话

var myVar = new celebrityID();

myVar.getID(); // myVar = 999

this like object creation from a class 这就像从类创建对象

So they can use it as 因此他们可以将其用作

var cid = celebrityID();
var celbId = cid.getID();

If you do not have the return statement the function getID() will not be useful and also celbId becomes undefined. 如果没有return语句,则函数getID()将无用,并且celbIdcelbId变为未定义。

If you closely observe, there is no return statement for setter. 如果您仔细观察,则没有针对setter的return语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM