理解Javascript块2返回?

理解Javascript块2返回?,javascript,angularjs,Javascript,Angularjs,我不太确定以下JS代码的作用: myApp.factory('helloWorldFromFactory', function() { return { sayHello: function() { return "Hello, World!" } }; }); 对于那些使用Angularjs的人来说,代码看起来很熟悉,但让我困惑的是这两个返回。我认为这是Javascript中的一种典型技术,但我以前从未见过这种技术 有人

我不太确定以下JS代码的作用:

myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!"
        }
    };
});
对于那些使用Angularjs的人来说,代码看起来很熟悉,但让我困惑的是这两个返回。我认为这是Javascript中的一种典型技术,但我以前从未见过这种技术


有人能帮我解释一下吗?

第一个
return
语句返回一个带有属性的对象文本。该属性是一个名为
sayHello
的函数

简化版本可能如下所示:

function getStuff() {
    return {
        someFunction: function() {
            return 'Hello World';
        }
    }
}
var o = getStuff();
console.log(o.someFunction());
var greeting = theObject['sayHello']();

当您运行该工厂时,它将为您提供一个对象:

{sayHello: function() {
    return "Hello, World!"
}}

第一次返回意味着什么。第二种意思是使用对象。sayHello,它将返回一个字符串“Hello,World!”。

使用角度术语的用法示例:

myApp.controller('MyCtrl', function ($scope, helloWorldFromFactory) {
    $scope.helloString = helloWorldFromFactory.sayHello();
});

让我们将其分解为不同的相关概念。首先,外部调用:

myApp.factory('helloWorldFromFactory', function() {
    // irrelevant for now
});
您正在调用
myApp
上的函数
factory
,并传递两个参数:一个字符串
“helloWorldFromFactory”
和一个函数。在JavaScript中,函数是第一类对象:这意味着您可以传递它们并将它们存储在变量中,就像您可以处理数字、字符串等一样。例如:

// Store a function into a variable myFunction
var myFunction = function(x) { return x*2; };

// Invoke the function through the variable
myFunction(5);

// Pass the function to another function
someFunction(myFunction);
好的,转到第一个函数体(
factory()
)的第二个参数):

这是一个返回JavaScript对象的函数,该对象包含属性
sayHello
。此属性可以是任何内容,但在本例中,它是另一个函数:

function() {
    return "Hello, world!"; 
}
// hypothetical code somewhere in the framework:
var theObject = yourStoredFunction();
首先,将函数传递给
factory()
。当有人调用该函数时:

function() {
    return "Hello, world!"; 
}
// hypothetical code somewhere in the framework:
var theObject = yourStoredFunction();
它将返回前面提到的对象。现在,如果其他一些代码像这样使用该对象:

function getStuff() {
    return {
        someFunction: function() {
            return 'Hello World';
        }
    }
}
var o = getStuff();
console.log(o.someFunction());
var greeting = theObject['sayHello']();

这将调用最里面的函数,并返回字符串
“Hello,world!”

外部函数返回一个带有方法的对象,就是它。您可以搜索“factory pattern”。这可能有助于您全面理解这一点。感谢您的深入回复。我感谢你的努力。