Hello I am messing with an object in Javascript. Here is my object in a seperate .js file.
json-webservice.js
//create object
function objdata(tool, product, details) {
//create object properties
this.tool = tool;
this.product = product;
this.details = details;
//create object methods
this.validate = function () {
var error = 0;
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
if (prop != 'validate' || prop != 'submit') {
if (this[prop] == null || this[prop] == undefined || this[prop] == "") {
error += 1;
}
}
}
}
return error;
}
this.submit = function () {
var error = this.validate();
if (error > 0) {
alert("errors: " + error);
}
else {
alert(this.tool + " " + this.product + " " + this.details);
}
}
}
}
I include this script in the head of my page index-main.html.
Then document ready, and then initialize the new object and submit.
$(document).ready(function () {
var userdata = new objdata('5', 'Main Page', '9');
userdata.submit();
});
My question is why does it only alert
---------------------------
Windows Internet Explorer
---------------------------
5
---------------------------
OK
---------------------------
and not
---------------------------
Windows Internet Explorer
---------------------------
5 Main Page 9
---------------------------
OK
---------------------------
like I think it should. Is my object correctly coded? I didn’t have any javascript errors reported in IE.
The wierd part is I can copy the json-webservice.js file contents (the object above) and it works perfectly. It does not work as an external file though.
You need to use
this[prop]rather thanthis.prop; the former looks for a property whose name is the string inprop, while the latter looks for a property whose name is literally “prop.”(I couldn’t get it to reproduce the output you had. As written, it was just alerting “error”, and the change above caused it to give the desired output.)