1、在原生js里面,我可以用原型继承。然后我就想问,在angular里面的继承和原型继承一样吗?如果一样好说,不一样,那么区别在哪里?或者说是用的方式有什么不同?
1、在原生js里面,我可以用原型继承。然后我就想问,在angular里面的继承和原型继承一样吗?如果一样好说,不一样,那么区别在哪里?或者说是用的方式有什么不同?
ng-repeat、ng-include、ng-switch、ng-view、ng-controller, 用scope: true和transclude: true创建directive。都会创建新的作用域且进行原型继承
angular里scope的继承也是使用的原型链,这个不用怀疑。angular是通过$scope.$new()
创建新的scope,看下$new方法的实现
$new: function(isolate, parent) {
var child;
parent = parent || this;
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
if (!this.$$ChildScope) {
this.$$ChildScope = createChildScopeClass(this);
}
child = new this.$$ChildScope();
}
...
},
接收两个参数
isolate 是否创建独立scope
parent 要继承的scope
isolate为true的话,不继承任何scope,为false才会去创建继承scope,核心在createChildScopeClass
,看下实现
function createChildScopeClass(parent) {
function ChildScope() {
this.$$watchers = this.$$nextSibling =
this.$$childHead = this.$$childTail = null;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$id = nextUid();
this.$$ChildScope = null;
}
ChildScope.prototype = parent;
return ChildScope;
}
相信到这里应该看出scope继承的原理了
ChildScope.prototype = parent;
13 回答13.1k 阅读
7 回答2.3k 阅读
3 回答1.4k 阅读✓ 已解决
6 回答1.5k 阅读✓ 已解决
2 回答1.5k 阅读✓ 已解决
3 回答1.5k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决