Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - Angular 2 templates methods vs getters

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

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

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

Over this:

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

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

Use methods vs getters to display calculated data.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Which after translation looks like:

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

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...