JavaScript |角 |控制器作为语法:不能使用`this` [英] JavaScript | Angular | Controller As Syntax: Cannot Use `this`

查看:26
本文介绍了JavaScript |角 |控制器作为语法:不能使用`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能使用控制器作为 this

谁能给我解释一下下面的场景吗?

作品

ng-controller="Parent as so"

休息时间

ng-controller="Parent as this"

使它成为关键字的单个字母 - 我想要 - 破坏了森林.

这是为什么?

附言我知道 vm 约定,但我发现它干扰了控制器/视图模型的可移植性.

解决方案

问题当然是不是 this 是 JavaScript 中的保留字.controller as 语法中没有任何规则表明您需要将 this 的值分配给与控制器同名的变量,我很确定angular 也不会做这样的事情.为什么会呢?使用 Function 构造函数会非常愚蠢,而且只是一个不必要的错误.

有一种简单的方法可以测试 JavaScript 保留字不是这里的问题.将您的控制器命名为throw".父级抛出".throw 是一个保留字,但它会throw 错误吗?不,那行得通吗?是的.

然而,

this 在 angular 自己的模板表达式的上下文中是保留的.用于引用表达式的当前scope.

{{记录(这个)}}

angular.module('testApp', []).controller('Parent', function($scope){this.test = 'foo';$scope.log = 函数(参数){控制台日志(参数);};});

以上不会抛出错误,但也不会记录控制器.相反,它会记录一个 scope 对象,其中包含 log 函数和 $parent 而不是什么.

事实上,它还包含一些我们感兴趣的东西:属性 this: Object,我们的控制器.

果然,将模板表达式更改为 {{log(this.this)}} 并且它会记录控制器实例就好了.尽管如此,仍然不会使用 'this' 作为名称,它可能只会导致比未定义函数更多的错误.

Cannot Use ControllerAs this

Can anyone explain the following scenario to me, please?

Works

ng-controller="Parent as thus"

Breaks

ng-controller="Parent as this"

That single letter which makes it a keyword -- which I want -- wrecks the forest.

Why is this?

P.S. I'm aware of the vm convention, but I find it disturbs portability of controllers/viewmodels.

解决方案

The problem is certainly not that this is a reserved word in JavaScript. There is no rule in the controller as syntax that says you would need to assign the value of this to a variable with the same name as the controller and I'm pertty sure angular won't do such thing either. Why would it? That would be incredibly stupid use of Function constructor and just a needless bug.

There's a simple way to test that JavaScript reserved words are not the issue here. Name your controller "throw". "Parent as throw". throw is a reserved word, but does that throw errors? No. Does that work? Yes.

this is, however, reserved in the context of angular's own template expressions. It's used to refer to the current scope of the expression.

<div ng-controller="Parent as this">
    {{log(this)}}
</div>


angular.module('testApp', []).controller('Parent', function($scope){
    this.test = 'foo';
    $scope.log = function(arg){
        console.log(arg);
    };
});

The above won't throw errors, but it won't log the controller either. Instead, it will log a scope object containing the log function and $parent and what not.

In fact, it will also contain something intresting to us: property this: Object, our controller.

And sure enough, change the template expression to {{log(this.this)}} and it will log the controller instance just fine. Still wouldn't use 'this' as the name though, it would probably just cause more bugs by mistake than undefined functions ever have.

这篇关于JavaScript |角 |控制器作为语法:不能使用`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆