Angular 2模板方法与getter [英] Angular 2 templates methods vs getters

查看:357
本文介绍了Angular 2模板方法与getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这样做是否有任何好处:

I'm wondering if there is any benefit to do this:

  <div>{{getSomething()}}</div>

  export class MyComp {
    getSomething() { return ...}
  }

超过此:

 <div>{{getSomething}}</div>

 export class MyComp {
   get getSomething() { return ...}
 }

使用方法与getter来显示计算数据。

Use methods vs getters to display calculated data.

推荐答案

我深入研究了这个并玩弄打字游戏Playground。
我用getter声明了两个类,第二个用你的问题中描述的get方法。

I looked deeper into this and played with typescript Playground. I declared two classes one with getter and the second with get method as described in your questions.

让我们看看它是什么样的:

Lets see how it looks like:

在第一个例子中,我们声明了一种以下列方式获取属性值的方法:

In the first example we declared a method for getting the property value in the following way:

class Greeter {
  greeting: string;
  constructor(message: string) {
      this.greeting = message;
  }
   getGreeting() {
      return this.greeting;
  }
}

翻译成javascript之后看起来像:

Which after translation to javascript it looks like:

var Greeter = (function () {
   function Greeter(message) {
       this.greeting = message;
   }
   Greeter.prototype.getGreeting = function () {
       return this.greeting;
   };
   return Greeter;
}());

关于我们以下列方式宣布吸气剂的第二个例子:

And regarding the second example where we declared a getter in the following way:

class GetterGreeter {
   _greeting: string;
   constructor(message: string) {
       this._greeting = message;
   }
    get greeting() {
       return this._greeting;
   }
}

翻译后的内容如下:

var GetterGreeter = (function () {
   function GetterGreeter(message) {
       this._greeting = message;
   }
   Object.defineProperty(GetterGreeter.prototype, "greeting", {
       get: function () {
           return this._greeting;
       },
       enumerable: true,
       configurable: true
   });
   return GetterGreeter;
}());

(您可以使用声明和javascript的翻译这里

(You can play with the declaration and the translation to javascript here)

正如您在get方法中看到的那样(如第一个示例中所示),该方法在原型和secon中声明d使用getter模式typescript的示例使用defineProperty api。

As you can see with get method (as in your first example) the method is declared on the prototype and in your second example using the getter pattern typescript uses the defineProperty api.

在这两种情况下,我们都在调用方法,而angular也会在更改检测期间调用方法来识别更改和重新渲染。

In both cases we are invoking a method and angular will also call a method during its change detection to identify changes and re-render.

正如我所看到的,这只是同一方法的语法糖,我认为其中一种方法没有任何性能优势。

As I see it this is only a syntactic sugar for the same approach and I don't see any performance benefit for one of the methods.

这篇关于Angular 2模板方法与getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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