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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With