0

Can't understand why ErrorHandler.prototype.errorsBasket after ajaxComplete got new value

var ErrorHandler = function() {
  var _this = this;
  $(document).ajaxComplete(function() {
    _this.errorsBasket.push([1]);
  });
};

ErrorHandler.prototype.errorsBasket = [];
ErrorHandler.prototype.errorsBasket1 = [];

var a = new ErrorHandler();
a.errorsBasket1 = [2];
$.get('/');

$(document).ajaxComplete(function() {
  why ->> console.log(ErrorHandler.prototype.errorsBasket); // [Array[1]] 
  console.log(ErrorHandler.prototype.errorsBasket1); // []
});

Link: http://jsfiddle.net/nBXAY/1/

4

1 回答 1

0

这样做时:

$(document).ajaxComplete(function() {
    _this.errorsBasket.push([1]);
});

ErrorHandler您正在更改object的值,它将为每个new ErrorHandler.

这样做时:

var a = new ErrorHandler();
a.errorsBasket1 = [2];

您正在为 分配一个新值a,这意味着如果您删除此行:

ErrorHandler.prototype.errorsBasket1 = [];

a.errorsBasket1 = [2];

它会起作用,但是

a.errorsBasket1; //without a.errorsBasket1 = [2];

将是未定义的。

然而这:

console.log(a.errorsBasket1); //without a.errorsBasket1 = [2];
ErrorHandler.prototype.errorsBasket1 = [0];
console.log(a.errorsBasket1);

会给

undefined
[0]

而这:

console.log(a.errorsBasket1); //with a.errorsBasket1 = [2];
ErrorHandler.prototype.errorsBasket1 = [0];
console.log(a.errorsBasket1);    

会给

[2]
[2]

总之,ErrorHandler.prototype.errorsBasket1 = [];只是一种为对象分配默认值的方法。

于 2013-10-29T12:39:57.757 回答