发布带有原型的javascript对象

时间:2015-12-01 17:05:37

标签: javascript jquery ajax oop

要求:

  • 我会创建一个包含方法和属性的javascript对象。
  • 我会发布这个对象。

我的代码:

        var SessionManager = (function (my) {
            function addUrl(urlHistory) {
                if (!urlHistory) throw new TypeError('"urlHistory" is null or not defined');
                if (!(urlHistory instanceof UrlHistory)) throw new TypeError('"urlHistory" is not an "UrlHistory" object');

                $.ajax({
                    url: '/CollateralManagement/Session/AddUrl',
                    type: 'POST',
                    success: function (result) {
                    },
                    data: { __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(), model: urlHistory }
                });
            }

        my.addUrl = addUrl;

        return my;
        })(SessionManager || {});

        var UrlHistory = function (area, controller, view, params) {
            if (params && !Array.isArray(params)) throw new TypeError('The variable "params" is not null and not an array');

            var me = this;

            me.Area = area;
            me.Controller = controller;
            me.View = view;
            me.Params = Array.isArray(params) ? params : [];
        };

        UrlHistory.prototype.coucou = function () {
            console.log(this);
        };

        UrlHistory.prototype.AddParam = function (key, value) {
            this.Params.push({ "Key": key, "Value": value });

            return this;
        };

        //I run the code with this exemple:
        var uh = new UrlHistory("toto", "tata", "titi");
        uh.AddParam("z", "z").AddParam("a", "a");
        SessionManager.addUrl(uh);

我的对象看起来很棒: UrlHistory {Area:" toto",Controller:" tata",View:" titi",Params:Array [2]}

但是当我输入ajax方法时,我有这个错误:

未捕获的TypeError:无法读取属性' push'未定义的

我尝试过相同的调用ajax而不添加原型,而且一切正常。

当运行ajax函数时,我的2个方法被调用但是"这个"是" Window"而不是" UrlHistory"。

问题:

  • 为什么在发布帖子时会调用方法?
  • 如何发布我的对象?

由于

2 个答案:

答案 0 :(得分:0)

以下代码将调用函数something

var Test = function(){
  this.name="Hello World";
}
Test.prototype.something = function(){
  console.log(".... something has been called",this);
  throw new Error("what is the stack?");
}

jQuery.post("",Object.create(new Test()))

这是因为jQuery代码中的following line检查对象成员是否是函数,如果是,它将调用该函数并使用结果值。

jQuery使用jQuery.param将对象序列化为http post或获取参数,以便jQuery.param(new Test())引发相同的错误。

您希望阻止jQuery调用该函数,但我在文档中找不到任何内容来覆盖序列化函数,但您可以在urlHistory类型中添加一个函数来转换为数据:

var urlHistory = function(){
  this.name="Hello World";
}
urlHistory.prototype.something = function(){
  console.log(".... something has been called",this);
  throw new Error("what is the stack?");
};
urlHistory.prototype.toData =  function(){
    var ret = {};
    //this works in your example but if nested objects have functions
    //  it may still fail
    for ( prefix in this ) {
        if(typeof this[ prefix ] !== "function" ){
          ret[ prefix ] = this[ prefix ];
        }
    }
    return ret;
}

console.log("..... working:",jQuery.param((new urlHistory()).toData()))

在您的情况下,您可以将toData添加到urlHistory,然后在ajax调用中执行:model: urlHistory.getData()

答案 1 :(得分:0)

我知道这个问题已经过时了,但这对我帮助很大,希望能帮到别人。

当通过ajax发送数据时,我只是编码并首先对其进行解码

var object //this is your object with a prototype
var send_data = $.parseJSON(JSON.stringify(object)); //this encodes and decodes 

$.ajax({
     url: '/someurl',
     type: 'post',
     data: send_data
})