<分区>
我正在编写一个小示例来调用函数 getAge()
以通过对象显示年龄。
我有 3 种方法可以做到这一点:
"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>
我的问题:最好的方法是什么?为什么?