On Thu, 03 Mar 2011 20:08:33 +0100, Jarek Foksa <[email protected]>
wrote:
When writing constructor functions it's very convenient to create "var
self = this" assignment so that we could easily access other
properties and methods even if default context has changed, for
example:
var Dialog = function() {
var self = this;
this.width = 400;
this.setWidth = function(newWidth) {
self.width = newWidth;
}
}
Notice that this creates a new function object for every Dialog object.
If you just did
Dialog.prototype.setWidth = function(newWidth) {
this.width = newWidth;
};
then you only create one function in total.
If you have many Dialog objects, it's a waste of memory.
I'm not sure why you want to be able to extract the setWidth function
and call it without the Dialog object present. It seems like premature
optimization. If you ever need to extract the function, you can use
myDialog.setWidth.bind(myDialog)
at that time.
But is it really a good idea to use "self" variable name for this
purpose? It seems to be already assigned to window object by default,
so I guess redefining it might break some third-party code.
It shouldn't. You declare "self" as local to the Dialog function.
That means that it's only visible to the code inside that function
(including nested functions). You shouldn't have third-party code
inside your own source code, so it won't be affected.
What other names would you recommend? Is there some other convention?
The name "self" is fine. I challenge the need for using it here.
/L
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]