I am from c# object oriented background and which to work similar priniciples in javascript. Any good I articles that could help with me research?
This is an example i put together for a Product Javascript object:
function Product() {
this.reset = function () {
this.id = 0;
this.name = '';
}
}
Product.prototype = {
loadFromJson: function (json) {
this.reset();
this.id = json.Id;
this.name = json.Name;
},
checkAvailability: function (qty) {
// Just to illustrate
return true;
}
};
So to create an instance of Product:
var p = new Product();
To access a public method:
var isAvailable = p.checkAvailability(1);
To access a public property:
var name = p.name;
Is the reset function I create a valid private function?
Is what I am doing above correct or is there a better way? I am new to this!
Also, if I create an instance of product in another javascript file, can I get intellisence on the properties of the Product object?
The reset is
this.reset();so that is in the scope of the object and thus could be called public, but remains in that scope. In your examplep.reset();butreset();fails.Better way? It depends, some circumstances require this complex, some do not. There are a number of ways to instantiate objects (everything is an object in JavaScript) and your examples are some of the ways.
No intellisence unless you build and attach your own (a LOT of work). (search on jQuery intellisence to see how that is done)
See this for some more regarding namespace. Note the internal and public functions and variables.