what does function () {} mean when assigned to a variable - javascript

I know that functions are objects in javascript, and that functions can be assigned to variables. I am also aware of this question: How does the (function() {})() construct work and why do people use it?.
But I would like to know precisely what does it mean in this context:
https://github.com/zsolt/retwis-nodejs/blob/master/domain.js#L43
User = function(){}
This line is followed by the declaration of some member functions (methods?) of the "supposed" User object.
It seems there is no other explanation answer here in SO.

It means User is a function that takes no inputs, has no side effects and returns nothing.
Most likely it is a class constructor and methods will be added to it later. User.foo = function() { /* ... */} would imply a static method, so this is more like a utilities class if you're used to thinking in Java architecture.
You should look up pseudo-classical inheritance in Javascript. Analogizing to Java, the code would be adding static methods to the User class, not object.
I'm still pretty convinced the code is following Java class patterns because the writer would prefer User to be a constructor that can be instantiated, has static methods, and has no instance methods (that I saw), over an object with properties that are functions. You are right that this is circuitous, but it's what the writer would do if they are a Java developer. It does have the advantage that instance methods may be added to User later with little client-code impact but I see no evidence this will happen to User (I didn't look long).
By the way, I deduced this because CapitalizedNames for functions implies it should be called with new in Javascript engineering in general, which implies it's a class. Figuring out why a class might be preferable just has to do with Java experience.

The canonical way to create an object in Javascript is:
function user(config) {
this.config = config;
...
}
User = new user(config);
It uses this context (and concept). This format is used if you want to create named properties and/or methods.
If you don't need to create this context you may use just following:
User = function(){}
Here the constructor function is anonymous and doesn't create any context. For the same reason the new keyword is not needed.

Related

Usecase for JavaScript prototype [duplicate]

I'd like to understand when it is appropriate to use prototype methods in js. Should they always be used? Or are there cases where using them is not preferred and/or incurs a performance penalty?
In searching around this site on common methods for namespacing in js, it seems that most use a non-prototype based implementation: simply using an object or a function object to encapsulate a namespace.
Coming from a class-based language, it's hard not to try and draw parallels and think that prototypes are like "classes" and the namespace implementations I mentioned are like static methods.
Prototypes are an optimisation.
A great example of using them well is the jQuery library. Every time you obtain a jQuery object by using $('.someClass'), that object has dozens of "methods". The library could achieve that by returning an object:
return {
show: function() { ... },
hide: function() { ... },
css: function() { ... },
animate: function() { ... },
// etc...
};
But that would mean that every jQuery object in memory would have dozens of named slots containing the same methods, over and over.
Instead, those methods are defined on a prototype and all jQuery objects "inherit" that prototype so as to gain all those methods at very little runtime cost.
One vitally important part of how jQuery gets it right is that this is hidden from the programmer. It's treated purely an optimisation, not as something that you have to worry about when using the library.
The problem with JavaScript is that naked constructor functions require the caller to remember to prefix them with new or otherwise they typically don't work. There is no good reason for this. jQuery gets it right by hiding that nonsense behind an ordinary function, $, so you don't have to care how the objects are implemented.
So that you can conveniently create an object with a specified prototype, ECMAScript 5 includes a standard function Object.create. A greatly simplified version of it would look like this:
Object.create = function(prototype) {
var Type = function () {};
Type.prototype = prototype;
return new Type();
};
It just takes care of the pain of writing a constructor function and then calling it with new.
When would you avoid prototypes?
A useful comparison is with popular OO languages such as Java and C#. These support two kinds of inheritance:
interface inheritance, where you implement an interface such that the class provides its own unique implementation for every member of the interface.
implementation inheritance, where you extend a class that provides default implementations of some methods.
In JavaScript, prototypical inheritance is a kind of implementation inheritance. So in those situations where (in C# or Java) you would have derived from a base class to gain default behaviour, which you then make small modifications to via overrides, then in JavaScript, prototypical inheritance makes sense.
However, if you're in a situation where you would have used interfaces in C# or Java, then you don't need any particular language feature in JavaScript. There is no need to explicitly declare something that represents the interface, and no need to mark objects as "implementing" that interface:
var duck = {
quack: function() { ... }
};
duck.quack(); // we're satisfied it's a duck!
In other words, if each "type" of object has its own definitions of the "methods", then there is no value in inheriting from a prototype. After that, it depends on how many instances you allocate of each type. But in many modular designs, there is only one instance of a given type.
And in fact, it has been suggested by many people that implementation inheritance is evil. That is, if there are some common operations for a type, then maybe it's clearer if they are not put into a base/super class, but are instead just exposed as ordinary functions in some module, to which you pass the object(s) you want them to operate on.
You should use prototypes if you wish to declare a "non-static" method of the object.
var myObject = function () {
};
myObject.prototype.getA = function (){
alert("A");
};
myObject.getB = function (){
alert("B");
};
myObject.getB(); // This works fine
myObject.getA(); // Error!
var myPrototypeCopy = new myObject();
myPrototypeCopy.getA(); // This works, too.
One reason to use the built-in prototype object is if you'll be duplicating an object multiple times that will share common functionality. By attaching methods to the prototype, you can save on duplicating methods being created per each new instance. But when you attach a method to the prototype, all instances will have access to those methods.
Say you have a base Car() class/object.
function Car() {
// do some car stuff
}
then you create multiple Car() instances.
var volvo = new Car(),
saab = new Car();
Now, you know each car will need to drive, turn on, etc. Instead of attaching a method directly to the Car() class (which takes up memory per each instance created), you can attach the methods to the prototype instead (creating the methods only once), therefore giving access to those methods to both the new volvo and saab.
// just mapping for less typing
Car.fn = Car.prototype;
Car.fn.drive = function () {
console.log("they see me rollin'");
};
Car.fn.honk = function () {
console.log("HONK!!!");
}
volvo.honk();
// => HONK!!!
saab.drive();
// => they see me rollin'
Put functions on a prototype object when you're going to create lots of copies of a particular kind of object and they all need to share common behaviors. By doing so, you'll save some memory by having just one copy of each function, but that's only the simplest benefit.
Changing methods on prototype objects, or adding methods, instantly changes the nature of all the instances of the corresponding type(s).
Now exactly why you'd do all these things is mostly a function of your own application design, and the kinds of things you need to do in client-side code. (A whole different story would be code inside a server; much easier to imagine doing more large-scale "OO" code there.)
If i explain in class based term then Person is class, walk() is Prototype method. So walk() will have its existence only after you instantiate new object with this.
So if you want to create the copies of object like Person u can create many users Prototype is good solution as it saves memory by sharing/inheriting same copy of function for each of the object in memory.
Whereas static is not that great help in such scenario.
function Person(){
this.name = "anonymous";
}
// its instance method and can access objects data data
Person.prototype.walk = function(){
alert("person has started walking.");
}
// its like static method
Person.ProcessPerson = function(Person p){
alert("Persons name is = " + p.name);
}
var userOne = new Person();
var userTwo = new Person();
//Call instance methods
userOne.walk();
//Call static methods
Person.ProcessPerson(userTwo);
So with this its more like instance method.
The object's approach is like Static methods.
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
Just including a video link here for reference, when not to use prototypes: https://youtu.be/JCXZhe6KsxQ?t=2m30s
Here is Ben Lesh's talk from NGConf, why rxjs removed patching prototype (chainable functions) in favor of pipeable functions.

Coding Style in node.js

Style 1: Objects with constructor/prototype
function DB(url) {
this.url = url;
}
DB.prototype.info = function (callback) {
http.get(this.url + '/info', callback);
};
Style 2: Closures
function DB(url) {
return { info: async.apply(http.get, url + '/info') };
}
This is just an example and assume that there are more prototype methods and private methods involved.
I have read in posts One and Two that closure style is much more preferred in nodejs over the other. Please help me clarify why using this.something syntax is bad in nodejs.
You can give your opinion about which is better, but I mostly need to know about what are the advantages and disadvantages of each style when used in nodejs.
It's not about a style. These two functions do two completely different things.
Closure provides an access to local variables. This way you can create private variables that aren't accessible from the outside (like url in your example). But it has a performance impact since closure is created each time your object is created.
Prototype function is faster, but it is created before object, and don't know anything about an object itself.
Sometimes it even makes sense to use both of them at the same time. :)
PS: coding style is described here: https://npmjs.org/doc/coding-style.html . It doesn't explain your particular question, but I feel I have to balance those two links in previous answer with something more sensible. :)
Closures, when done correctly, allow you to encapsulate data through the use of the scope chain that cannot be modified by any other caller.
The prototype chain does not provide any protection in that same sense. The main drawback to the use of Objects in the fashion you describe, especially in a server or library scenario, is that the "this" keyword can be modified by the caller. You have no control over that and your code will break in wildly unpredictable ways if it occurs.
var mongo = new DB('localhost');
mongo.info.call(this); // broken
Now it may not happen as explicitly as that but if you are passing around objects or object properties as event handlers, callbacks, etc into other functions, you have no way of knowing - or protecting against - that type of usage. So the bottom line is that the 'this' keyword is not something you can bank on. While you can completely control your immediate scope with the use of closures.
In a similar vein, you also have no guarantee that your object's prototype chain has not been altered. Unless, of course, you are creating a closure over the object and returning a wrapper.
Lastly, the closure structure more closely follows the Law of Demeter since your object would, theoretically, be "reaching through" via the prototype chain. Using a closure to encapsulate other calls allows you to expose a single method which can result in calls to another service methods. This provides greater maintainability and flexibility since you now control the methods you expose directly without relying on the prototype chain. Of course, the LoD is just one way of doing things so that may or may not be important to you.
Node follow javascript standards. So any javascript coding style is a proper coding style for node.js. But the following links may give you the abbreviation of node.js coding style.
http://nodeguide.com/style.html
http://innofied.com/javascript-coding-standards-follow/
I use sjsClass: https://www.npmjs.org/package/sjsclass
Code example:
Class.extend('DB', {
'protected url': null,
__constructor: function (url) {
this.url = url;
},
info: function (callback) {
http.get(this.url + '/info', callback);
}
});
There are benefits to both styles and i think it depends on what your module/file is trying to expose. I heavily use closure style for most modules i use in my code. (like db abstraction, cache abstraction, mail etc..) and i use constructors/prototype for objects i create a lot of (like a node in a doubly-linked-list)
=== objects with attributes defined inside a closure
if you create an object (lets call it self),
inside its scope add a bunch of methods that access and attach to that object (self.x)
and at the end export self, everything has access only to what you added to self and cannot access the local variables inside the function where you created self
=== constructors and prototype
on the other hand if you create constructors and add methods/fields to them trough prototype every function that attaches itself to your instance has access to its internal variables and state.
==
there are some things that work easier with prototypes like EventEmitter
and Streams but it not very hard to attach them to objects also.
Javascript is both an object oriented language and functional language, and missing the heavy lifting tools on both sides
like proper inheritance ever seen this.super().super().someMethod() ?? I havn't
(you need it if both superclasses have the same method name)
or nomads or simple generators at the side of functional programming.
so for me it makes sense to use both, and pick the one that's most suited to your problem.
EDIT
There is one big benefit for objects which i totally forgot about.
In your second example you use a flow control library (async in this case but any defered library will do), it makes your code so much cleaner, however
for your example to work the get method of http.get has to be bound to http, which in many cases it is not. so then your code will look like http.get.bind(http)
if http were an object and get was defined in its scope it would always work and allows you to pass it around to other code. (like async)
IMHO this is discussion is larger than node ... it's about javascript language.
So I suggest read this:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
and google a lil about javascript design patterns!
constructor can be use like that
var db = new DB();
...
if(db instanceof DB){
...
}
Closures can make private variables like
function DB(url) {
var urlParam = '&a=b';
return {
info: async.apply(http.get, url + '/info' + urlParam)
};
}
urlParam is a private variables cannot be get or set
if you only want a static class or simple class, use Closures.

Is it customary JS to write getters for simple properties?

Is this code idomatic, or should I just acess the properties directly?
self.isAlive = function() {
return self.alive;
}
It all depends on implementation.
If you feel the property is always going to be the value, accessing the property is adequate. If you feel like there's going to be some logic that determines returning a "properly formatted" value, I would use a method (or if the value could possibly be dynamic based on other factors, a method is a good idea).
To go a step further, other languages like C# have properties making it safe to expose values, but not necessarily alter them. JS doesn't have such a method of protecting it, so often get<Var> is used to expose the property, but in a read-only fashion.
It's all about how you would like the data, while also trying to anticipate what the worst-case scenario could be if you expose the property directly vs. through a method.
It seems that you are speaking of properties in the classical OOP sense, i.e., properties of classes. In the current version of Javascript, simulating this behavior is not completely clean. Consider the following example:
var Widget = function() {
var private = 'private';
}
'Widget' is a constructor function, and 'private' will be instantiated in the scope of just the constructor function. That means there is only one way to get access to 'private' from outside the constructor function scope:
var Widget = function() {
var private = 'private';
this.getPrivate = function() {
return private;
}
}
This will hide the private variable for each instance of Widget, but unfortunately, 'getPrivate' must now be added to each instance of Widget. You can see this occurring in the constructor function by the statement this.getPrivate = .... Every time you make an instance of Widget using var widget1 = new Widget(), that specific instance will have a new function, 'getPrivate', added to it.
The normal way to make reusable components in Javascript is to use its implementation of Prototypical Inheritance. You assign a prototype object to the constructor function that will have shared methods and properties across all instances of the component. I will provide an example below to explain, but there are caveats to prototypical inheritance that you should become aware of if you are doing object-oriented javascript. A great resource.
Here's an example of how this might come in to play for your example:
var Widget = function() {
this.alive = true;
}
Widget.prototype.isAlive = function() {
return this.alive;
}
var widget1 = new Widget();
widget1.isAlive(); // returns true
The problem here is that the property alive is being added to the object, and thus, it is publicly available, i.e., any user of your Widget can simply look through the DOM in their favorite variation of FireBug and see (as well as freely modify) this property.
Consider a variation where you attempt to hide alive to external users. Because alive is a property of Widget instances, you would want to include the code to hide it in the constructor, as shown below:
var Widget = function() {
var alive = true;
}
However, as stated at the beginning of this post, alive in this case is only exposed to the constructor function's scope; therefore, it would not be accessible to methods on the prototype. The reason for this is that each of those methods do not have the same scope as the constructor function, since Javascript only has function scope.
In conclusion, if you're trying to hide data in a reusable component, javascript does not provide a clean way to do it. If you don't mind having new memory allocated on each component instance for the same methods, then you can use my second code example in this post. However, if you prefer to have your methods allocated in memory only once, then you will need to expose properties on the object instance, e.g., this.alive = true.
That's subjective. Use of getters and setters is very discussed. Some people (like me) say you should always use getters and setters to follow the encapsulation principle, while others say that you shouldn't since your application would become unmaintainable.
This is good practice if you don't want outside js code to modify your property. If this is the desired effect you might consider assigning that property using var instead of making it a property of that object. That way your code within the object can modify it but it can only be accessed through your getter
var alive = false;
function isAlive(){ return alive;}
You can use:
function isAlive(){
return arguments.callee.alive;
}
isAlive.alive=true;
This appears to be ok still in strict mode.
Another way to accomplish this is
function isAlive(){
return isAlive.alive;
}
isAlive.alive=true;
But the problem is that someone can use the name as a string, or rename the function etc... and you can loose the status.

Javascript when to use prototypes

I'd like to understand when it is appropriate to use prototype methods in js. Should they always be used? Or are there cases where using them is not preferred and/or incurs a performance penalty?
In searching around this site on common methods for namespacing in js, it seems that most use a non-prototype based implementation: simply using an object or a function object to encapsulate a namespace.
Coming from a class-based language, it's hard not to try and draw parallels and think that prototypes are like "classes" and the namespace implementations I mentioned are like static methods.
Prototypes are an optimisation.
A great example of using them well is the jQuery library. Every time you obtain a jQuery object by using $('.someClass'), that object has dozens of "methods". The library could achieve that by returning an object:
return {
show: function() { ... },
hide: function() { ... },
css: function() { ... },
animate: function() { ... },
// etc...
};
But that would mean that every jQuery object in memory would have dozens of named slots containing the same methods, over and over.
Instead, those methods are defined on a prototype and all jQuery objects "inherit" that prototype so as to gain all those methods at very little runtime cost.
One vitally important part of how jQuery gets it right is that this is hidden from the programmer. It's treated purely an optimisation, not as something that you have to worry about when using the library.
The problem with JavaScript is that naked constructor functions require the caller to remember to prefix them with new or otherwise they typically don't work. There is no good reason for this. jQuery gets it right by hiding that nonsense behind an ordinary function, $, so you don't have to care how the objects are implemented.
So that you can conveniently create an object with a specified prototype, ECMAScript 5 includes a standard function Object.create. A greatly simplified version of it would look like this:
Object.create = function(prototype) {
var Type = function () {};
Type.prototype = prototype;
return new Type();
};
It just takes care of the pain of writing a constructor function and then calling it with new.
When would you avoid prototypes?
A useful comparison is with popular OO languages such as Java and C#. These support two kinds of inheritance:
interface inheritance, where you implement an interface such that the class provides its own unique implementation for every member of the interface.
implementation inheritance, where you extend a class that provides default implementations of some methods.
In JavaScript, prototypical inheritance is a kind of implementation inheritance. So in those situations where (in C# or Java) you would have derived from a base class to gain default behaviour, which you then make small modifications to via overrides, then in JavaScript, prototypical inheritance makes sense.
However, if you're in a situation where you would have used interfaces in C# or Java, then you don't need any particular language feature in JavaScript. There is no need to explicitly declare something that represents the interface, and no need to mark objects as "implementing" that interface:
var duck = {
quack: function() { ... }
};
duck.quack(); // we're satisfied it's a duck!
In other words, if each "type" of object has its own definitions of the "methods", then there is no value in inheriting from a prototype. After that, it depends on how many instances you allocate of each type. But in many modular designs, there is only one instance of a given type.
And in fact, it has been suggested by many people that implementation inheritance is evil. That is, if there are some common operations for a type, then maybe it's clearer if they are not put into a base/super class, but are instead just exposed as ordinary functions in some module, to which you pass the object(s) you want them to operate on.
You should use prototypes if you wish to declare a "non-static" method of the object.
var myObject = function () {
};
myObject.prototype.getA = function (){
alert("A");
};
myObject.getB = function (){
alert("B");
};
myObject.getB(); // This works fine
myObject.getA(); // Error!
var myPrototypeCopy = new myObject();
myPrototypeCopy.getA(); // This works, too.
One reason to use the built-in prototype object is if you'll be duplicating an object multiple times that will share common functionality. By attaching methods to the prototype, you can save on duplicating methods being created per each new instance. But when you attach a method to the prototype, all instances will have access to those methods.
Say you have a base Car() class/object.
function Car() {
// do some car stuff
}
then you create multiple Car() instances.
var volvo = new Car(),
saab = new Car();
Now, you know each car will need to drive, turn on, etc. Instead of attaching a method directly to the Car() class (which takes up memory per each instance created), you can attach the methods to the prototype instead (creating the methods only once), therefore giving access to those methods to both the new volvo and saab.
// just mapping for less typing
Car.fn = Car.prototype;
Car.fn.drive = function () {
console.log("they see me rollin'");
};
Car.fn.honk = function () {
console.log("HONK!!!");
}
volvo.honk();
// => HONK!!!
saab.drive();
// => they see me rollin'
Put functions on a prototype object when you're going to create lots of copies of a particular kind of object and they all need to share common behaviors. By doing so, you'll save some memory by having just one copy of each function, but that's only the simplest benefit.
Changing methods on prototype objects, or adding methods, instantly changes the nature of all the instances of the corresponding type(s).
Now exactly why you'd do all these things is mostly a function of your own application design, and the kinds of things you need to do in client-side code. (A whole different story would be code inside a server; much easier to imagine doing more large-scale "OO" code there.)
If i explain in class based term then Person is class, walk() is Prototype method. So walk() will have its existence only after you instantiate new object with this.
So if you want to create the copies of object like Person u can create many users Prototype is good solution as it saves memory by sharing/inheriting same copy of function for each of the object in memory.
Whereas static is not that great help in such scenario.
function Person(){
this.name = "anonymous";
}
// its instance method and can access objects data data
Person.prototype.walk = function(){
alert("person has started walking.");
}
// its like static method
Person.ProcessPerson = function(Person p){
alert("Persons name is = " + p.name);
}
var userOne = new Person();
var userTwo = new Person();
//Call instance methods
userOne.walk();
//Call static methods
Person.ProcessPerson(userTwo);
So with this its more like instance method.
The object's approach is like Static methods.
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
Just including a video link here for reference, when not to use prototypes: https://youtu.be/JCXZhe6KsxQ?t=2m30s
Here is Ben Lesh's talk from NGConf, why rxjs removed patching prototype (chainable functions) in favor of pipeable functions.

Calling a class which contains a constructor to setup click events etc?

I am trying to organize my JavaScript. What I would like to do is have a class for each PAGE rather then just entering JavaScript straight into a js - is this good practice?
Let me explain: thinking along the lines of is it a good or bad idea on my variable naming. Remember that this a kind of class so I have to create the class but then I must call it (see below). I am using the prototype and constructor pattern.
// THIS FILE WILL BE SAVED as RESERVATIONPAGE
function ReservationPage(){
// Setup click events in this constructor
$('submit-button').bind('click',this.submit_click);
$('clear-button').bind('click',this.clear_click);
// setup other variables
}
ReservationPage.prototype = {
constructor: ReservationPage,
submit_click : function () {
alert(' you just clicked the submit button');
},
clear_click : function () {
alert('button for clearning the form fields!!');
}
};
Then each page will need a standard js file i.e. not a class / object to instantiate their Page js like above, so a kind of entry point - so hence:
// THIS FILE WILL BE SAVED as ReservationLoad - notice the word Load :-) -- don't know if this is good naning convetion, anybody suggest anything different??
var reservationPage = new ReservationPage(); // CREATES NEW INSTANCE OF THE CLASS/OBJECT ..
I don't any other way of doing it; I would really appreciate any input. I will be using jQuery extensively but this shouldn't matter. I need a standard JS file - no objects to instantiate my objects hence I called in load. This in turn instantiates the object and calls the constructor.
The constructor sets up the click events and then calls the methods.
Is this good?
Any idea where I am going wrong?
I really appreciate some input as I am little lost and want to do it right. I am coming from a C# .NET background, and I know js isn't a proper OOP language but I am trying to treat it like this for better structuring.
This way, all my js files are separate from my HTML and my CSS; there are no events entered into the html, they are all entered via code
Look forward to any info
JavaScript is a proper OOP language. It's not class-based like you're used to (it's prototype-based), but it is absolutely object-oriented -- very much so.
You can simulate classes and class-based inheritance in JavaScript (it's that powerful), which can be useful for people like you (and me) with backgrounds in that world. But classes are not the only way to modularize, which is really what you're talking about doing.
The solution presented in your question creates a function backed by an object (the prototype) which you can then use to create another object (the instance) that then does what you want. That fits the class-based mindset (which may be a good enough reason to do it!), and it's what I do for things I may need to create more than one of, but in some sense it may be overkill for this purpose, since you're not going to have multiple instances of your page objects at any given time. It also means that your click handlers won't work as defined in your example code -- when they're called in response to a click, the this value will be wrong, it won't point to your ReservationPage instance. (Functions in JavaScript are just functions, they're not methods; this is defined by how the function is called, not how it's defined. Surprising to people like us, but it turns out that it's incredibly useful.) That can be worked around, of course, but it requires...working around it.
Since you're only going to need one instantiated object for the page, rather than all the hassle of constructor functions and prototypes such, why not just have one object for the page? And you can use a closure (function) to put scope around that object so it can have easily-accessed variables without having to worry about this and without polluting the global namespace. Here's an example of doing that:
// Create a closure (function) to scope our variables, assign its
// return value to a variable for our page
var reservationPage = (function() {
var somePageData; // A private variable for our page
// Our load function; we'll export that below
function onLoad() {
// Hook some elements
$('submit-button').bind('click', submit_click);
$('clear-button').bind('click', clear_click);
// Set up some page data
somePageData = 42;
}
// A private function for handling the click of the submit button
function submit_click() {
alert('You just clicked the submit button; page data is ' + somePageData);
}
// A private function for handling the click of the clear button
function clear_click() {
alert('You just clicked the clear button; page data is ' + somePageData);
}
// Export any functions we may need outside the closure
return {onLoad: onLoad};
})();
$(document).ready(reservationPage.onLoad);
Note that all of the functions have access to the somePageData variable, and to each other, but we didn't have to worry about this. That's because the functions are declared within the scope in which the somePageData is declared, and so they "close over" it (have access to it). That access is "live", it's not a copy or something.
Note that I've wrapped the entire thing in a function. I'm doing that because we want to avoid just dumping everything in the global namespace, because A) it's the Right Thing(tm), and B) you're combining all of your pages into one file you reuse. You could have four or five (or 20) page objects in your combined file, all definining a var with that same name, and they'd be kept distinct because they're declared inside separate functions. Similarly, the functions for the page (onLoad and the like) are scoped to the function. Using a scoping function like this is called the "module pattern."
I also didn't bother to export any more than I had to make public (just the onLoad function). There's no need for our handlers to be available outside the closure.
Another aspect of the above that can be useful: All of the functions we care about have names. Named functions help tools help you, by telling you where an exception occurred, etc. There's a big difference, from a tool's point of view, between an anonymous function assigned to a variable:
var fname = function() { /* ... */ };
...and a named function:
function fname() { /* ... */ };
This is just a side-note, though; you can do that with the code in your question, too:
ReservationPage.prototype = (function(){
function submit_click() {
alert(' you just clicked the submit button');
}
function clear_click() {
alert('button for clearning the form fields!!');
}
return {
constructor: ReservationPage,
submit_click: submit_click,
clear_click: clear_click
};
})();
Now, I wouldn't use the "one object" pattern for anything general purpose that I might want more than one of; that's what classes (or things like classes) are for. Hence the links above to simulating classes and solving the this problem. :-) But for modularizing and organizing the script that's specific to the page, classes may be overkill.

Categories

Resources