简体   繁体   English

奇怪的AngularJS初学者行为

[英]Strange AngularJS beginner behavior

I am starting learning AngularJS but I've stumbled across a strange behavior I can't quite understand where the (() => {}) notation is not equivalent to (function(){}). 我开始学习AngularJS,但偶然发现了一个奇怪的行为,我不太了解(()=> {})表示法在什么地方不等同于(function(){})。

My index.html: 我的index.html:

<!DOCTYPE html>
<html ng-app="gemStore">
  <head>
    <title>AngularJS Store</title>
    <script src="./angular.min.js"></script>
    <script src="./app.js"></script>
  </head>
  <body>
    <div ng-controller="StoreController as store">
      <h1>{{store.product.name}}</h1>
      <h2>${{store.product.price}}</h2>
      <p>{{store.product.description}}</p>
    </div>
  </body>
</html>

My app.js (closure stripped for debugging). 我的app.js(关闭了用于调试的外壳)。

var app = angular.module('gemStore', []);

app.controller("StoreController", function() {
    this.product = gem;
});

var gem = {
    name: 'Dodecahedron',
    price: 2.95,
    description: '. . .'
};    

In app.js, if I change 在app.js中,如果我更改

app.controller("StoreController", function() {
    this.product = gem;
});

to

app.controller("StoreController", () => {
    this.product = gem;
});

My page no longer displays the gem information(just blanks and the dollar sign remain). 我的页面不再显示宝石信息(仅保留空白和美元符号)。

Can somebody explain why this happens? 有人可以解释为什么会这样吗?

AngularJS version: v1.5.6 AngularJS版本:v1.5.6
Opera version: 37.0.2178.54 Opera版本:37.0.2178.54

You shouldn't use arrow functions if you need this context. 如果需要this上下文,则不应使用箭头功能。

Read more here(13.2): http://exploringjs.com/es6/ch_arrow-functions.html 在此处(13.2)了解更多信息: http : //exploringjs.com/es6/ch_arrow-functions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM