Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to call a function in javascript [closed]

I'm writing a small example to call function getAge() to display age via an object.

I've 3 ways to do that:

"use strict";
var personClass = class {
  static getAge() {
    return 18
  }
};

var personJSON = {
  getAge: function () {
    return 18
  }
};

function personFunc() {
  var getAge = function () {
    return 18
  };
  
  // set a flag to point to getAge function
  this.getAge = getAge()
}

$('#btn1').click(function () {
  alert(personClass.getAge())
});

$('#btn2').click(function () {
  alert(personJSON.getAge())
});

$('#btn3').click(function () {
  var p = new personFunc();
  alert(p.getAge)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">Get age via class</button>
<button id="btn2">Get age via json</button>
<button id="btn3">Get age via function</button>

My question: What's the best way? And why?

like image 271
Tân Avatar asked Jan 19 '16 07:01

Tân


1 Answers

It depends on the actual problem you have to solve and the style of programming you're using. If you tend to use an object oriented approach and want to benfit from it's features like inheritance you might want to model a person as

function Person(){
    var age = 18;
    this.getAge = function() {
        return age; 
    }
}

var person = new Person();
alert(p.getAge());

Or as a class

class Person {
  constructor() {
    this.age = 18;
  }

  getAge() {
    return this.age()
  }
}

If you prefer a more functional style, you'll write pure and independent functions that perform some action on some data:

// does not make much sense in this age of a person context
function age(obj, dateFn) {
    return dateFn() - obj.born;
}

var person = { born : new Date(/* */) }
var animal = { born : new Date(/* */) }
alert(age(person, Date.now));
alert(age(animal, Date.UTC));

For the example of getAge, any kind of static function does not make any sense (your first example), since age is the property of some object. So you'll need an instance of an object which you can use to call a method, or to pass to a function.

like image 137
hansmaad Avatar answered Sep 19 '22 06:09

hansmaad