Home >Web Front-end >JS Tutorial >Does AngularJS Always Use Prototypal Inheritance for Child Scopes?
Nuances of Scope Prototypal / Prototypical Inheritance in AngularJS
Question:
Quick Answer:
Child scopes normally prototypically inherit from their parent scopes through APIs such as ng-repeat, ng-switch, ng-include, but not always. One exception is directives with scope: {...} which creates isolate scopes that do not inherit prototypically.
Long Answer:
JavaScript Prototypal Inheritance
Objects in JavaScript are linked through prototypes, which form a chain of inheritance. A child object can access properties and methods from its parent prototype, even if they are not directly defined on the child.
In the example below, childScope inherits from parentScope:
// parentScope object parentScope = { aString: 'parent string', anArray: [1, 2, 3], anObject: { prop1: 'parent prop1' }, aFunction: function() { console.log('parent output'); } }; // childScope object inherits from parentScope childScope = Object.create(parentScope);
Angular Scope Inheritance
AngularJS leverages prototypal inheritance for its scopes. Scopes primarily deal with data and functions in your application. Child scopes typically inherit from their parent scopes and can access their properties and methods.
However, there are exceptions and nuances to be aware of:
ng-include and ng-switch
These directives create new scopes that inherit prototypically from the parent scope, but beware of binding to primitives (e.g., numbers, strings, booleans) from the child scope. It may lead to unexpected behavior due to child scope property hiding. Consider using objects, $parent, or parent scope functions instead.
ng-repeat
Ng-repeat creates child scopes with a twist. It assigns a new property to the child scope with the value of the iterated item. If the item is primitive, this can result in independent copies that do not affect the parent array. However, if the item is an object, the reference is shared, and changes in the child scope will be reflected in the parent array.
Directives
Conclusion
Prototypal inheritance is a fundamental aspect of AngularJS scoping. The above nuances and exceptions help you avoid pitfalls and use inheritance effectively in your applications. Remember to consider data types, scope types (e.g., isolate), and the possibility of property hiding when working with multiple scopes.
The above is the detailed content of Does AngularJS Always Use Prototypal Inheritance for Child Scopes?. For more information, please follow other related articles on the PHP Chinese website!