【发布时间】:2015-12-01 17:05:36
【问题描述】:
要求:
- 我会创建一个带有方法和属性的 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 {区域:“toto”,控制器:“tata”,视图:“titi”,参数:Array[2]}
但是当我输入 ajax 方法时出现这个错误:
Uncaught TypeError: Cannot read property 'push' of undefined
我尝试了同样的调用ajax,没有添加原型,一切都OK。
运行 ajax 函数时,我的 2 个方法被调用,但“this”是“Window”而不是“UrlHistory”。
问题:
- 为什么在发帖时会调用方法?
- 如何发布我的对象?
谢谢
【问题讨论】:
-
您在创建 SessionManager Prototype 时是否使用了“类”?否则 addUrl 附加到窗口对象。请显示更多代码。
-
似乎
this.Params未定义。也许this不是您所期望的?试着调试一下你的代码! -
TJHeuvel,请读到最后。当我在这里使用我的方法时:“uh.AddParam("z", "z").AddParam("a", "a");" “this”是“UrlHistory”(这是正常的)但是当调用ajax运行时,我的方法再次被调用并且“this”是“Window”并且参数是“undefined”,为什么?
标签: javascript jquery ajax oop