无法使用$ .post()发布javascript对象

Edi*_*iba 0 javascript jquery

我正在尝试创建一个javascript对象,以便我可以稍后将其发布到我的后端,但我遇到了一些麻烦.

这是我正在尝试的代码.当我将console.log创建到对象时,一切都很好,但是当我发布它时,$.post我遇到了一些错误.我认为错误正在发生,因为在对象中我有一个方法,可能会导致问题,但我需要该方法动态生成对象.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使console.log()everythings是我想要的节目,但问题是当我想使用$ .post()将此对象发布到php文件

$.post('/api.php', {api: appointments}, function(){
    console.log('test')
});
Run Code Online (Sandbox Code Playgroud)

我明白了 Cannot read property 'push' of undefined

我创建了一个jsfiddle来帮助您理解我的问题.

Tom*_*Tom 5

你有一个范围问题;

this.part = new Array();
this.addPart = function(obj){
    this.part.push(obj);
}
Run Code Online (Sandbox Code Playgroud)

您的使用function(obj)创建了自己的范围,具有自己的this变量.所以,this.part设置不一样this.part = new Array();

要解决,我们一个箭头功能;

this.part = new Array();
this.addPart = (obj) => {
    this.part.push(obj);
}
Run Code Online (Sandbox Code Playgroud)

箭头函数表达式具有比函数表达式更短的语法,并且不绑定它自己的this,arguments,super或new.target.

这是你jsFiddle的分叉版本,向你展示它的工作原理.