【问题标题】:What is 'this' in angular decorator?角装饰器中的“这个”是什么?
【发布时间】:2016-09-21 13:29:26
【问题描述】:

我正在浏览这个doc,我的困惑是link.apply(this,attrs)中的“this”是什么。有人可以帮忙吗?

 $provide.decorator('fooDirective', function($delegate) {
    var directive = $delegate[0];

    directive.scope.fn = "&";
    var link = directive.link;

    directive.compile = function() {
      return function(scope, element, attrs) {
        link.apply(this, arguments);
        element.bind('click', function() {
          scope.$apply(function() {
            scope.fn();
          });
        });
      };
    };

    return $delegate;
   });
 });

当我尝试使用控制台调试器对其进行调试时,'this' 在链接函数运行时未定义。

【问题讨论】:

标签: angularjs angular-directive angular-decorator


【解决方案1】:

Angular 装饰器中没有特殊的this 上下文,因此它可能是松散模式下的window 或严格模式下的undefined

在嵌套函数中this 可能引用非词法上下文,这可能发生在 Angular 指令中:

directive.compile = function() {
  // `this` is directive DDO in compile function
  return function(scope, element, attrs) {
    // `this` is `undefined` in link function
    ...
  };
};

compile 函数中this 是指令DDO。在controller 函数中this 是控制器实例。 link 函数中没有词法 this

link.apply(this, arguments) 是为了安全起见,但这只是一种误导。可能是link.apply(null, arguments)

【讨论】:

    【解决方案2】:

    您需要创建一个编译函数,该函数将返回您的新链接函数。
    在那里,您在旧链接函数中调用 apply(作为第一个参数传递函数本身)来获取旧功能。
    使用该设置,您只需要添加额外的行为(在这种情况下,您将单击事件绑定到将在单击时调用新函数的元素)。

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 2021-05-10
      • 2018-09-12
      • 2018-03-27
      • 1970-01-01
      • 2013-12-27
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多