Javascript类的全局变量值丢失
问题描述:
我得到了一个带有全局变量和方法的JavaScript类,并且一个specefic方法使得一些引用。Javascript类的全局变量值丢失
DOOM = (function() {
/** Class VALIDATIONS **/
var validation = function (form, inputDiv, action) {
this.form = form;
this.inputDiv = inputDiv; // -- This Variable
this.action = action; // -- And This Variable
};
validation.prototype = {
validate: function (rules, messages) {
this.rules = rules;
this.messages = messages;
console.log(inputDiv); // -- here still have value
console.log(inputDiv);
$(this.form).validate({
rules: this.rules,
messages: this.messages,
submitHandler: function(form){
var getDom = new DOOM.DOM();
var data = getDom.buildJSONValuesByJSON(getDom.buildJSONObjByForm(inputDiv)); // -- But here, already haven't value
var sendData = new DOOM.callAJAX(action);
sendData.start(data);
console.log('[submitHandler] = '+ data);
return false;
},
作为解决方法,我必须在全局变量仍有价值的地方分配值。但我的问题是,为什么这些变量失去了他的价值?
答
函数的参数列表中指定的变量始终是局部变量,而不是全局变量。所以在validation()
构造函数中,inputDiv
是一个局部变量。如果您在validation.prototype.validate()
中执行console.log(inputDiv)
时发现了某些内容,它必须来自您发布的代码之外声明的其他变量。
要访问提供给方法中构造函数的inputDiv
,您需要使用this.inputDiv
。
validation.prototype = {
validate: function (rules, messages) {
this.rules = rules;
this.messages = messages;
var inputDiv = this.inputDiv;
console.log(inputDiv);
$(this.form).validate({
rules: this.rules,
messages: this.messages,
submitHandler: function(form){
var getDom = new DOOM.DOM();
var data = getDom.buildJSONValuesByJSON(getDom.buildJSONObjByForm(inputDiv));
var sendData = new DOOM.callAJAX(action);
sendData.start(data);
console.log('[submitHandler] = '+ data);
return false;
},
+0
其实,我也这么做。非常感谢你的解释。现在我明白了如何在JavaScript上更好地使用这些变量 – CR7
inputDiv'的'第二外观是一个不同的功能,内侧[其具有不同的范围。](http://*.com/questions/500431/what-is-the-scope-of-变量在JavaScript中) – Blazemonger
'inputDiV'和'action'不是全局变量,它们是'validation'函数中的局部变量。 – Barmar
你应该使用'this.inputDiv'。 – Barmar