简体   繁体   中英

Why does this result in inheritance?

I was reading this article on scope inheritance in AngularJS and was confused by this code example:

angular.module("Demo", [])  
  .controller("ChildCtrl", function($rootScope, $scope) {
    $rootScope.rootyThing = "I am groot";
    console.log($scope.rootyThing);  // "I am groot"
    console.log(Object.getPrototypeOf($scope)); // Scope
 });

I don't understand why $scope.rootyThing is set instead of undefined .

The article's explanation seems incomplete. The fact that the child scope "prototypically inherits" from $rootScope would not explain this, seeing as rootyThing is not set on the prototype, and moreover was set after the creation of the child scope $scope .

The only explanation is if the scopes in Angular are deeply modified such that all variables set on them are broadcast to existing child scopes. Unless I'm missing something, more than possible.

Can anyone explain this?

Edit: My current understanding is that $rootScope is in fact the Scope function itself rather than an instance of Scope , and all $scope instances use this as a root prototype, so when variables are set on the function Scope then they're naturally accessible to the various $scope instances.

Is this accurate?

All scopes are added on $rootScope object. If you add a property(for example someProperty)on $rootScope and you try to access it using $scope.someProperty , then it will be checked that this property exists on $scope (ie current scope). If that property does not exist, then it will be checked on higher level in scope chain(ie $rootScope ).

ng-controller will create a new Scope .

this scope's prototype is set to parent Scope (ie, $rootScope in this case)

And it's the default javascript behavior to look in the prototype chain if the property which we are looking for is not found in the object.

范围继承

It is set to the prototypes, try console.log

$scope.__proto__.rootyThing

And you should see it there.

Furthermore, objects are by reference in javascript so it doesnt matter when $scope was set for example

//say this is your rootScope
objRoot = {
   obj: {
       test: 'hello'
   }
}

//Now lets create a scope
var temp = objRoot.obj

//Update rootScope
objRoot.obj.test = "changed"

//log your temp
console.log(temp.test); //changed

In AngularJs, as far as I know, the scopes are inherited from the parent scope, all the variables , but if u have a sibling scope then those values will not be inherited. The broadcasting is done for events.

So, Angular is working as it has to be. If you have set some variable on the $rootScope that will be accesible throughout the App.

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