简体   繁体   中英

Why don't you have to refer to an “intermediate” object in an Angular.js factory, when accessing the factory's objects?

I'm plugging along at this tutorial: https://thinkster.io/mean-stack-tutorial

Which defines an Angular.js factory using this code:

app.factory('posts', [function(){
  var o = {
    posts: []
  };
  return o;
}]);

What I don't understand is that later in the controller, to populate the variable $scope.posts, the following code is used:

$scope.posts = posts.posts;

This works, while:

$scope.posts = posts.o.posts;

does not. I don't understand how you can access the "posts" variable in the "posts" factory directly; is this because by typing the code:

return o

all of the o objects's code is now considered to be part of the "posts" factory's code?

Variable o is not a property of the factory, it is just a temporary local variable. The factory source code is equivalent to:

app.factory('posts', [function(){
  return {
     posts: []
  };
}]);

In general, this code:

var x = <some expression>;
return x;

is equivalent to:

return <some expression>;

This is beacause you are returning the entire object.

For exemple you can simplify this code:

app.factory('posts', [function(){
  var o = {
    posts: []
  };
  return o;
}]);

like this:

app.factory('posts', [function(){
  return {
    posts: []
  };
}]);

It has the same logic, and you clearly canot do that posts.o.posts ...

Imagine this in simpler terms.

Take a piece of code like this:

function foo()
{
    var bar = {
        baz: 5
    };

    return bar;
}

var myVar = foo();

At this point myVar refers to the bar that foo() created. It doesn't refer to foo() 's variables altogether.

So, to access bar.baz , you would do myVar.baz . You wouldn't do myVar.bar.baz .

The factory in Angular is essentially the same scenario, just wrapped as an Angular factory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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