javascript - angular里面的作用域继承是怎么实现的的?
PHPz
PHPz 2017-04-11 13:30:03
[JavaScript讨论组]

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

PHPz
PHPz

学习是最好的投资!

全部回复(3)
PHP中文网
$scope   $rootscope
巴扎黑

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;

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号