angular 装饰器中的 'this' 是什么?
What is 'this' in angular decorator?
我正在经历这个 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' 未定义,而 link 函数是 运行。
您需要创建一个编译函数,它将 return 您的新 link 函数。
在那里,您在旧 link 函数中调用 apply(将函数本身作为第一个参数传递)以获取旧功能。
使用该设置,您只需要添加额外的行为(在这种情况下,您将点击事件绑定到元素中,该元素将在点击时调用新函数)。
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)
而不是。
我正在经历这个 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' 未定义,而 link 函数是 运行。
您需要创建一个编译函数,它将 return 您的新 link 函数。
在那里,您在旧 link 函数中调用 apply(将函数本身作为第一个参数传递)以获取旧功能。
使用该设置,您只需要添加额外的行为(在这种情况下,您将点击事件绑定到元素中,该元素将在点击时调用新函数)。
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)
而不是。