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

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

问题描述

有人可以向我解释以下情况吗?

Can anyone explain the following scenario to me, please?

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.

为什么会这样?

PS我知道 vm 约定,但我发现它扰乱了控制器/视图模型的可移植性。

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

推荐答案

问题肯定是 这个是JavaScript中的保留字。
控制器中的语法中没有规则表明你需要将这个的值赋给一个具有相同值的变量作为控制器命名,我确定角度不会做这样的事情。为什么会这样?那将是非常愚蠢地使用 Function 构造函数而只是一个不必要的bug。

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.

有一种简单的方法来测试JavaScript保留字不是这里的问题。将控制器命名为throw。 父母投掷 throw 是一个保留字,但抛出错误?不,那有用吗?是的。

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.

是保留在angular自己的模板表达式的上下文中。它用于表示表达式的当前范围

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);
    };
});

以上不会抛出错误,但也不会记录控制器。相反,它会记录一个范围对象,其中包含 log 函数和 $ parent 以及不。

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.

事实上,它还会包含一些对我们有用的东西:property this:Object ,我们的控制器。

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

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

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天全站免登陆