angular里面的作用域继承是怎么实现的的?

1、在原生js里面,我可以用原型继承。然后我就想问,在angular里面的继承和原型继承一样吗?如果一样好说,不一样,那么区别在哪里?或者说是用的方式有什么不同?

阅读 2.8k
3 个回答

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;

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题