继承的作用
继承允许一个 angularjs 作用域,访问它的父作用域,一直到根作用域为止,angularjs 的继承和 js 的原型链实现大概一致,实际使用中由于继承的作用域可以访问所有的父作用域,最好还是尽可能少使用继承而使用隔离作用域
根作用域
我们一直在单独的一个 scope 上工作,这个 scope 没有父亲,它就是很典型的的根作用域,在实际使用中
我们不会使用 new 的方式来创建一个作用域,应该只有一个根作用域通过 $rootScope 注入,它的后代通过 controllers 和 directive 创建。
$new
首先要做的就是
- 让子作用域可以访问父代作用域
- 让父作用域不能访问子作用域
- 子作用域可以监听父作用域的属性
多个作用域不交叉
it('can be nested at any depth', function() {const a = new Scope();const aa = a.$new();const aaa = aa.$new();const aab = aa.$new();const ab = a.$new();const abb = ab.$new();a.value = 1;expect(aa.value).to.equals(1);expect(aaa.value).to.equals(1);expect(aab.value).to.equals(1);expect(ab.value).to.equals(1);expect(abb.value).to.equals(1);ab.anotherValue = 2;expect(abb.anotherValue).to.equals(2);expect(aa.anotherValue).to.equals(undefined);expect(aaa.anotherValue).to.equals(undefined);});
单例模式
Scope.prototype.$new = function () {const ChildScope = function() { };ChildScope.prototype = this;const child = new ChildScope();return child;}
要做到上面几点只需要这几条代码即可,每一个 parent 调用的 $new 都会返回拥有不同父类状态的实例,做到了作用域不交叉
Scope.prototype.$new = function () {class ChildScope extends Scope{}return new ChildScope()}
最初我的想法是上面代码,但是这样写之后,使得使用的子作用域都一致了,并没有起到作用
影子属性
it('shadows a parents property with the same name', function() {var parent = new Scope();var child = parent.$new();parent.name = 'Joe';child.name = 'Jill';expect(child.name).toBe('Jill');expect(parent.name).toBe('Joe');});
我们不用修改代码即可做到,因为这是根据 js 的原型链的原理实现的,在子作用域上定义一个父作用域已有的属性并不会修改父作用域的值,在作用域上定义的属性,不会对父作用域有任何影响,只会对子作用域有影响。
分散 watcher
既然子作用域可以继承所有的方法包括 $watch 和 $digest 那么实际上,watchers 都存放在根作用域下,导致每次调用 $digest 都会遍历所有的 watchers 我们真正想要的是,只遍历所在的被调用 $digest 所在的 scope 。
it('does not digest its parent(s)', function () {const parent = new Scope();const child = parent.$new();parent.aValue = 0;parent.$watch(function (scope) {return scope.aValue},function (newValue, oldValue, scope) {parent.anotherValue = 1;})child.$digest();expect(parent.anotherValue).to.equals(undefined);});
Scope.prototype.$new = function () {const ChildScope = function() {};ChildScope.prototype = this;const child = new ChildScope();child.$$watchers = [];return child;}
循环 digest
现在我们考虑到了向上 digest(调用子作用域的 $digest 不会遍历父作用域的),我们现在考虑向下 digest,考虑到子作用域可能在 watch 父作用域上的属性,但是只能遍历自己的数组,当父作用域属性改变时我们调用 $digest 时不仅会遍历自身的还会调用子作用域的,我们想要 fix 这个问题。
it('can digest its child', function () {const parent = new Scope();const child = parent.$new();parent.aValue = 'abc';child.$watch(function (scope) {return scope.aValue},function (newValue, oldValue, scope) {scope.anotherValue = newValue;})parent.$digest();expect(child.anotherValue).to.equals('abc');});
为了实现在 parent 上调用 $digest 会执行 child 上的 watcher ,我们需要让在每一个作用域上都调用 $digest ,我们构建一个帮助函数,它会在每个子作用域上执行一次参数函数,直到这个函数返回 false。
Scope.prototype.$$everyScope = function(fn) {if (fn(this)) {return this.$$children.every(function(child) {return child.$$everyScope(fn);});} else {return false;}};
Scope.prototype.$$digestOnce = function () {let dirty,continueLoop = true,self = this;self.$$everyScope(function (scope) {let newValue, oldValue_.forEachRight(scope.$$watchers, function (watcher) {try {if (watcher) {newValue = watcher.watchFn(scope);oldValue = watcher.last;if (!scope.$$areEqual(newValue, oldValue, watcher.valueEq)) {self.$$lastDirtyWatch = watcher;watcher.last = (watcher.valueEq ? _.cloneDeep(newValue) : newValue);watcher.listenerFn(newValue,(oldValue === initWatchVal ? newValue : oldValue),scope);dirty = true;} else if (self.$$lastDirtyWatch === watcher) {continueLoop = false;return false;}}} catch (err) {console.log(err);}})return continueLoop;})return dirty;}
- 从 parent.$digest 出发,第一次 $digestOnce 时,执行 $$everyScope ,首先在对于根作用域调用 fn(this) ,此时会遍历整个顶层作用域的 $$watchers 数组,因为 $$areEqual 此时肯定为 false ,所以 fn(this) 返回 true ,接着遍历 $$children 数组对于每个子作用域调用 fn(this) ,此时 $$areEqual 此时肯定还为 false,所以 fn(this) 返回 true,由于它现在没有 child ,所以直接返回 true 结束了 $$everyScope。
- 此时根作用域仍为 dirty ,且 $$lastDirtyWatch 是子作用域的最后一个 watcher ,接着再调用一次 $$digestOnce ,执行 fn(this) , 再次遍历所有子作用域,但是这次更新 $$lastDirtyWatch 。
- 这是因为由于只存在子作用域监听和改变父作用域上的属性,所以当子作用域的 $$everyScope 返回 false 就说明子作用域上的函数没有再改变父作用域上的值。这就是为什么 $$lastDirtyWatch 始终取的是根作用域的原因。
- 如果有新的赋值语句,请重新调用 parent.$digest
- 实际上 angularjs 没有,是用一系列 $$nextSibling, $$prevSibling, $$childHead, and $$childTail 来实现的,但是本质上和数组一样,只是会让操作消耗更少的资源。
$apply
现在的 $digest 只作用于该节点往下的节点,调用 $apply 的时候我们希望是从根节点往下遍历的it('digests from root on $apply', function() {const parent = new Scope();const child = parent.$new();const child2 = child.$new();parent.aValue = 'abc';parent.counter = 0;parent.$watch(function(scope) { return scope.aValue; },function(newValue, oldValue, scope) {scope.counter++;});child2.$apply(function(scope) {});expect(parent.counter).to.equals(1);});
我们在本作用域调用 eval ,但是从根部遍历。为什么我们会让它从根部开始,因为引入外部代码,我们不确定究竟改动了哪块内容,不如直接整体遍历。如果你要节省性能最好使用 $digest 。Scope.prototype.$apply = function (expr) {try {this.$beginPhase('$apply');return this.$eval(expr);} finally {this.$clearPhase();this.$root.$digest();}};
$evalAsync
虽然 push 进了本作用域的数组,但是从根部开始遍历。Scope.prototype.$evalAsync = function (expr) {const self = this;if (!self.$$phase && !self.$$asyncQueue.length) {setTimeout(function () {if (self.$$asyncQueue.length) {self.$root.$digest();}}, 0);}self.$$asyncQueue.push({scope: self, expression: expr});};
$$lastDirtyWatch
我们在所有用到 $$lastDirtyWatch 的地方前面加一个 $root 来保证遍历算法可以进行隔离作用域
现在的子作用域和父作用域之间过于亲密,我们希望一方面子作用域仍属于继承的一部分,但是不会继承父作用域的任何属性,它从作用域链中隔离了。我们将 $new 第一个参数作为是否隔离的判断条件,隔离后不可以直接获得父作用域的值,不可以监听父作用域的任何值。
但是我们知道隔离作用域并没有完全和它的父作用域隔离,而是定义了一个 map 来说明我们可以从父作用域获取的值,我们之后会讨论Scope.prototype.$new = function(isolated) {let child;if (isolated) {child = new Scope();} else {const ChildScope = function() {};ChildScope.prototype = this;child = new ChildScope();}this.$$children.push(child);child.$$watchers = [];child.$$children = [];return child;};
$digest, $apply, $evalAsync, 和 $applyAsync
由于隔离作用域我们需要重新看一遍 $digest, $apply, $evalAsync, and $applyAsync 这些函数, 后三个都从最顶层开始 digest ,$digest 在每个 scope 中都引入来 watcher 数组。
我们希望 $apply 仍然从顶部作用域开始 diegstit('digests from root on $apply when isolated', function() {const parent = new Scope();const child = parent.$new(true);const child2 = child.$new();parent.aValue = 'abc';parent.counter = 0;parent.$watch(function(scope) { return scope.aValue; },function(newValue, oldValue, scope) {scope.counter++;});child2.$apply(function(scope) {});expect(parent.counter).to.equals(1);});
$evalAsync 同理。it('schedules a digest from root on $evalAsync when isolated', function(done) {const parent = new Scope();const child = parent.$new(true);const child2 = child.$new();parent.aValue = 'abc';parent.counter = 0;parent.$watch(function(scope) { return scope.aValue; },function(newValue, oldValue, scope) {scope.counter++;});child2.$evalAsync(function(scope) {});setTimeout(function() {expect(parent.counter).to.equals(1);done();}, 50);});
child.$root,child.$$asyncQueue,child.$$postDigestQueue,$$applyAsyncQueue,这四个利用父作用域的影子属性拿到顶层作用域的值。Scope.prototype.$new = function(isolated) {let child;if (isolated) {child = new Scope();child.$root = this.$root;child.$$asyncQueue = this.$$asyncQueue;child.$$postDigestQueue = this.$$postDigestQueue;child.$$applyAsyncQueue = this.$$applyAsyncQueue;} else {const ChildScope = function() {};ChildScope.prototype = this;child = new ChildScope();}this.$$children.push(child);child.$$watchers = [];child.$$children = [];return child;};
我们希望 child 调用 digest 时,会让遍历顶层的数组,但是隔离作用域进行 $$applyAsyncId 判断时会创建一个新的属性,而不是使用顶层的所以总是为 undefined ,只有在任何使用到 $$applyAsyncId 的地方前面加上 $root 即可。it("executes $applyAsync functions on isolated scopes", function(done) {const parent = new Scope();const child = parent.$new(true);let applied = false;parent.$applyAsync(function() {applied = true;});child.$digest();expect(applied).to.equals(true);});
销毁 scope
在实际程序运行过程中,时刻存在着 scope 作用域的膨胀和缩小 ```jsx Scope.prototype.$destroy = function() { if (this.$parent) {
} this.$$watchers = null; };const siblings = this.$parent.$$children;const indexOfThis = siblings.indexOf(this);if (indexOfThis >= 0) {siblings.splice(indexOfThis, 1);}
Scope.prototype.$new = function(isolated, parent) { let child; parent = parent || this; if (isolated) { child = new Scope(); child.$root = this.$root; child.asyncQueue = this.asyncQueue; child.postDigestQueue = this.postDigestQueue; child.applyAsyncQueue = this.applyAsyncQueue; } else { const ChildScope = function() {}; ChildScope.prototype = this; child = new ChildScope(); } this.children.push(child); child.watchers = []; child.$$children = []; child.$parent = parent; return child; }; ```
