0

I am trying to create a javascript object so i can post it to my backend later but i am having some trouble with this.

This is my code that i am trying. When i make console.log to the object everything is fine but when i post it with $.post i got some errors. I think that error is comming because in the object i have a method and that might be causing the problem but i need that method to genereate object dynamically.

var appointmentsPart = {  
    "id":"appointments",
    "integrationId":"1258514282"
}


var appointments = new objectPart('appointments', '1258514282');

appointments.addPart(appointmentsPart);

console.log(appointments); //this shows the correct object

function objectPart(id, integrationId){
    this.id  = id;
    this.integrationId = integrationId;
    this.part = new Array();
    this.addPart = function(obj){
        this.part.push(obj);
    }
}

When i make console.log() everythings is shows like i want but the problem is when i want to post this object to a php file using $.post()

$.post('/api.php', {api: appointments}, function(){
    console.log('test')
});

I get Cannot read property 'push' of undefined

I have created a jsfiddle to help you understand my problem.

2
  • jsfiddle is empty Commented May 9, 2017 at 11:33
  • @AlivetoDie i updated it check it now Commented May 9, 2017 at 11:34

3 Answers 3

5

You have a scoping issue here;

this.part = new Array();
this.addPart = function(obj){
    this.part.push(obj);
}

Your use of function(obj) creates its own scope, with its own this variable. So, this.part isn't the same one set in this.part = new Array();

To solve, us an arrow function;

this.part = new Array();
this.addPart = (obj) => {
    this.part.push(obj);
}

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

Here's a forked version of you jsFiddle to show you it working.

Sign up to request clarification or add additional context in comments.

1 Comment

correct and detailed explanation.+1. up-voted others too
3

In your this.part.push this shows not to objectPart function, but to addPart function. Miss-use of this; save this to variable to use it inside other function.

1 Comment

Thank you this fixed my issue.
2

The reason for the error is that this is referring to nothing. Change your code to this to get array push to work.

function objectPart(id, integrationId){
    this.id  = id;
    this.integrationId = integrationId;
    this.part = new Array();
    var arr = this.part;
    this.addPart = function(obj){
        arr.push(obj);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.