Neil W Neil W - 1 year ago 60
Javascript Question

Javascript Objects / Prototypes. Is my understanding wrong

I have been reading about Javascript Classes / Objects / Prototypes and come from a OOP background so I now wish to use Objects in Javascript.

However I think I am misunderstanding something. When using objects in the past in for example you created your object and was able to populate it by using dataclasses.

But here in the land of javascript things dont execute in the way I was expecting due to this async thing.

So I create my prototype as below and call the appropriate function but the function says it has fnished (but hasnt because it hasnt had a response from the $.post that is taking place, my code continues as null values and I dont get the info I want.

<!DOCTYPE html>

<button onclick="gogetperson()">Hello</button>
<p id="demo"></p>

function Person() {
this.firstName = '-';
this.surname= '-';
this.alias = 0;
} = function() {
return this.firstName + " " + this.surname

Person.prototype.getPerson = function(personid)
var query = $.param({personid: personid});
var url = 'custom/person_get.php';

$.post(url, query, function (response) {
var obj = $.parseJSON(response);
this.firstname= obj['rFirstName'];
this.surname = obj['rLastName'];
this.alias = obj['rAlias'];



function gogetperson()
var myPerson = new Person();


<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>


So when my button runs the gogetperson function it finishes but has not got the data yet.
The console.log in the $.post section returns to the console the first name of my person but too late for me to use it.

Am I using prototypes in the wrong way?

I want to be able to use javascript as an object when getting data.

Or am I totally wrong.

My reason for wanting to use it this way was it seems the better choice over php objects.

Should I use PHP objects instead?

I ultimately want to get data from a mysql database and easily change my webpage with jquery and javascript.

Answer Source

You are missing one thing ,that is http call using $.post is asynchronous and it is not a blocking call. In order to get values back from getPerson() method, you have to pass a callback ( or function) in that function to get the result back but it is not a recomended approach . You can read about promises and use them because they are great. However using a callback, you can do something like.

Person.prototype.getPerson = function(personid, cb)
    var query = $.param({personid: personid});
    var url = 'custom/person_get.php';

    $.post(url, query, function (response) {
        var obj = $.parseJSON(response);
        var person = new Person();
        person.firstname= obj['rFirstName'];
        person.surname = obj['rLastName'];
        person.alias = obj['rAlias'];




And then you can call it like,

var myPerson = new Person();
function showPersonDetails(person){
myPerson.getPerson(1, showPersonDetails);