Accessing 'this' in Javascript closure - javascript

This is more of a sanity check than anything else. I've found that when working with closures in Javascript I often use the following pattern to access the enclosing class from within the function:
MyClass.prototype.delayed_foo = function() {
var self = this;
setTimeout(function() {
self.foo(); // Be nice if I could use 'this' here
}, 1000);
};
Obviously this works just fine, and it's not even a big hassle to work with. There's just this little itch in the back of my brain that says 'You're making this too complicated, dummy!' Is this the commonly accepted pattern?

This is the commonly accepted pattern with the exception that that is often used instead of self.

You can pull a sneaky using a binding function like this:
var Binder = function(fnc, obj) {
return function() {
fnc.apply(obj, arguments);
};
};
and then changing your call to
MyClass.prototype.delayed_foo = function() {
setTimeout(Binder(function(){
this.foo("Lols");
},this), 1000);
};
jsfiddle example:
http://jsfiddle.net/ctrlfrk/6VaV6/

Related

Why would an event listener in a JavaScript class see old context variable?

so I'm having a problem that seems to defy everything I know about how scope is handled in JavaScript with anonymous functions - but it could be something else I'm not thinking about.
I have a JavaScript object, called Element, with a constructor similar to this:
function Element(boxElement) {
var self = this;
// Set jquery instance variables
self.pageElement = null;
self.boxElement = boxElement;
... blah blah blah
// Implement triggers to empty functions
self.onElementClicked = function () {};
// Bind listeners
self._bind_listeners();
}
The bind_listeners method is defined as such
Element.prototype._bind_listeners = function() {
var self = this;
self.boxElement.on('click', function (e) {
// Don't handle if handled already
if (e.isDefaultPrevented()) return;
console.log("Got past the return");
self.onElementClicked();
});
};
And there's also a method to set the callback method onElementClicked:
Element.prototype.on_element_click = function(callback) {
var self = this;
self.onElementClicked = callback;
};
The problem I am encountering is that if I set my callback using the on_element_click method, my method doesn't see the current instance - it sees what the instance would look like just after construction.
More specifically to my situation, there's an instance variable called boxElement that refers to a JQuery element - and in Chrome's console I can see that the instance (self) still does refer to the correct element on the page, but the onElementClicked instance variable (and others) do not seem to be set from within the listener.
Feel free to revise my explanation or ask for clarification.
From the implementer perspective:
If I do this:
// Set default listener for element click
formElement.on_element_click(function () {
console.log("Hello");
});
The listener never says Hello because onElementClicked doesn't appear to be set.
However, if I instead do this:
formElement.boxElement.click(function () {
console.log("Hello");
});
It successfully says "Hello" and makes me confused.
I found the solution to my specific problem, which is a good example of how an error like this can occur. (offtopic: please feel free to add answers for other ways to produce this error - it is a very non-intuitive problem and will always be caused by an external factor)
It turns out the class I was testing with is a class that extends my Element class - BUT, it does so improperly / VERY VERY badly!
As embarrassing as it is to post this, here's the original constructor of my "subclass" (quotes for reasons soon apparent):
function StrikeoutFormElement (formElement) {
var self = this;
// Set reference to form element
self.fe = formElement;
$.extend(self, self.fe);
// Override methods
self.on_reposition(function () {
self._on_reposition();
});
}
I used JQuery's object extending function and a hacky workaround to override something. I have learned the hard way to NEVER use JQuery's extend for OOP, as it is only intended for data manipulation rather than as a language tool.
The new constructor looks like this:
function StrikeoutFormElement (elem) {
var self = this;
}
// Extend the FormElement prototype
StrikeoutFormElement.prototype = Object.create(Element.prototype);
StrikeoutFormElement.prototype.constructor = Element;
This is a method described in an MDN article somewhere. I'll post the source when I find it if someone doesn't beat me to it.
Shoutout to anyone who looked at this obscure problem and attempted to figure it out!

Proper way for defining services and factories in AngularJS

I read some tutorials for AngularJS and noticed, that everyone is using a slightly different approach how to define a service. I'm wondering whats the best method, or what drawbacks could arise when using a specific approach.
The first difference I noticed, is in using an anonymous function OR a named function:
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
angular.module('myApp').service('myService', function() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
Is there any difference in this two methods?
Does angular provide the myService named function? And how?
The second difference is in defining the "public methods", e.g. what is visible to the outside:
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
this.doSomething = function() {
return "bar";
};
this.var1 = _var1
});
The first one returns an object, which acts like an interface and defines what is visible to the public. The second one, defines its methods and properties with this.
Are there any drawbacks?
Why would I prefer one method over the other?
The third difference is on defining services like this:
var Session = function() {};
Session.prototype.doSomething = function() {
return "bar";
};
Session.prototype.var1 = "foo";
angular.module('myApp').service('myService', Session);
Here, I only see one drawback, that privat variables cannot be shared with other functions. But does this method has any big advantages? I could imagine that for factories (not services) the performance would be better, because the prototype functions only has to be defined once, and not everytime a new object is created (because a service is a singleton, a factory not).
Defining and using factories: I'm also unsure, if the following method is best practise when using factories:
angular.module('myApp').factory('User', function() {
var User = function(data) {
angular.extend(this, {
id: null,
email: null,
name: null
}, data);
};
return User;
});
And when using the factory, I'm writing new User(data). data gets merged with some default variables etc. What do you think about this method? Is there a big drawback? Or am I using factories in a wrong way?
I think that by and large most of what you're asking - and the reason that you're seeing it done differently - is that these are stylistic differences that are all completely legit JavaScript. There's no real best practices here.
The first question - it makes no difference.
The second question - both work, I have a strong personal preference for the first because it's more flexible; there are nifty tricks you can do that way, object manipulation kind of stuff. You could probably do all of them operating on "this" but it feels unnecessary to me. Again, personal preference.
The third question - this is just a feature of JavaScript which supports first class functions. It's just a language feature and it's going to come down to how you prefer to design things. I inline them but keep each service in its own file. I think that you see people doing it this way because the Angular Documentation on Services shows them doing it that way because it was easier to read in documentation. But it's not much different really.
I don't have a problem with how you're using that factory, but make sure you don't actually want $resource.

scope Issue seeing object methods

I have tried searching through a lot of S.O. pages but nothing has touched EXACTLY on this top while also NOT USING JQUERY.... I am trying to stick to pure JavaScript as I want to learn it 115% before advancing my current knowledge of JQuery.
I have an object called ScreenResizeTool like this...
function ScreenResizeTool(currImg) {
window.addEventHandler('resize', function() {
listen(currImg);
}, true);
}
and a method like this...
ScreenResizeTool.prototype.listen = function(currImg) {
//Random Code For Resizing
};
My trouble is probably obvious to an experienced JavaScript user but I am having trouble not making this into a messy dirty awful OOP set. I have done various tests to show and prove to myself that the this inside the addEventHandler changes when it becomes bound to the window. This much I assumed before testing but I was able to see that once window.resize event happens the listen method is gone and not a part of the global window variable....
I have also tried adding a this capture such as this.me = this inside the object constructor however it also couldn't see the me variable once it ran. Once the window took the function over it no longer knew anything about the me variable or any reference to my class methods....
I am aware that I could separate this differently but my goal here is to learn how to fully encapsulate and use as many clean OOP structures as possible as I just came from the .NET world and I need it in my life.
I am also aware that I could make messy calls and or store this object or access to the methods inside the window variable but that seems outright wrong to me. I should be able to fully encapsulate this object and have its events and methods all implemented in this class structure.
I also know that the currImg variable is not going to be seen either but lets start small here. I assume once I figure out my incorrect train of thought on scope for JavaScript I should be fine to figure out the currImg problem.
I know there's 1000 JavaScript programmers out there waiting to rip me a new one over asking this simple question but I gotta know...
Thoughts anyone?
this inside a function bound to a DOM Object (like window) will always refer to that object.
this inside a constructor function will always refer to the prototype.
A common practice to circumvent the this issue, as you mentioned, is to cache it in a variable, often called self. Now you want the variables and properties of your object available after instantiation, so what you need is the return keyword, more specifically to return the parent object itself. Let's put that together:
function ScreenResizeTool() {
var self = this;
// method to instantiate the code is often stored in init property
this.init = function() {
window.addEventListener('resize', function() {
self.listen(); // self will refer to the prototype, not the window!
}, true);
};
return this;
}
ScreenResizeTool.prototype.listen = function() { // Dummy function
var h = window.innerHeight, w = window.innerWidth;
console.log('Resized to ' + w + ' x ' + h + '!');
};
Pretty easy huh? So we have our prototype now, but prototypes can't do anything if there's not an instance. So we create an instance of ScreenResizeTool and instantiate it with its init method:
var tool = new ScreenResizeTool();
tool.init();
// every time you resize the window now, a result will be logged!
You could also simply store the listen & init methods as private functions inside your constructor, and return them in an anonymous object:
function ScreenResizeTool() {
var listen = function() { ... };
var init = function() { ... };
// in this.init you can now simply call listen() instead of this.listen()
return {
listen: listen,
init: init
}
}
Check out the fiddle and make sure to open your console. Note that in this case I'd rather use the first function than the second (it does exactly the same) because prototypes are only useful if you have multiple instances or subclasses
The whole concept of this in JavaScript is a nightmare for beginners and in my code I usually try to avoid it as it gets confusing fast and makes code unreadable (IMHO). Also, many people new to JavaScript but experienced in object-oriented programming languages try to get into the whole this and prototype stuff directly though the don't actually need to (google JS patterns like IIFE for example as alternatives).
So looking at your original code:
function ScreenResizeTool(currImg) {
window.addEventHandler('resize', function() {
listen(currImg); // global function listen?
}, true);
}
ScreenResizeTool.prototype.listen = function(currImg) {
//Random Code For Resizing
};
First off, you probably mean addEventListener instead. In its callback you refer to listen but as a global variable which would look for it as window.listen - which doesn't exit. So you could think to do this:
function ScreenResizeTool(currImg) {
window.addEventHandler('resize', function() {
this.listen(currImg); // what's this?
}, true);
}
As you want to use the prototype.listen function of ScreenResizeTool. But this won't work either as the event listener's callback function is called with a different this and not the this that is your function scope.
This is where something comes in which makes most programmers cringe, you have to cache this, examples from code I've seen:
var _this = this;
var that = this;
var _self = this;
Let's just use the latter to be able to refer to the function within the event callback:
function ScreenResizeTool(currImg) {
var _self = this;
window.addEventListener('resize', function() {
_self.listen();
}, true);
}
Now this will actually work and do what you want to achieve: invoke the prototype.listen function of ScreenResizeTool.
See this JSFiddle for a working example: http://jsfiddle.net/KNw6R/ (check the console for output)
As a last word, this problem did not have anything to do with using jQuery or not. It's a general problem of JS. And especially when having to deal with different browser implementations you should be using jQuery (or another such library) to make your own code clean and neat and not fiddle around with multiple if statements to find out what feature is supported in what way.

Javascript Prototype function and SVG setAttribute(onclick)

Trying to use an svg onClick to call a prototype function.
Usually to call a prototype function I would just do this.(functionName) but when I put it into the .setAttribute(onclick, "this.(functionName)") it does not recognise the prototype function. Has anyone had any experience in this?
In case the above wasn't clear heres the basic jist of it...
function myobject(svgShape) {
this.svgshape.setAttribute(onclick, 'this.doSomething()');
}
myobject.prototype.doSomething = function() {
alert("works");
}
Three things that may help:
1) First off, I think you're missing this line from the top of your myobject function:
this.svgshape = svgshape;
I'm assuming that was just an error posting the question and have inserted that below.
2) Normally when you're using Prototype (or any modern library), you don't use strings for callbacks, you use functions. Also, you normally assign handlers using the library's wrapper for addEventListener / attachEvent (observe, in Prototype's case) rather than the old DOM0 attribute thing. So:
function myobject(svgShape) {
this.svgshape = svgshape;
$(this.svgshape).observe('click', this.doSomething); // STILL WRONG, see below
}
myobject.prototype.doSomething = function() {
alert("works");
}
3) But JavaScript doesn't have methods (it doesn't really need them), it just has functions, so the above won't ensure that this (the context of the call) is set correctly. With Prototype you'd use bind to set the context:
function myobject(svgShape) {
this.svgshape = svgshape;
$(this.svgshape).observe('click', this.doSomething.bind(this));
}
myobject.prototype.doSomething = function() {
alert("works");
}
(Or you can use your own closure to do it. The advantage of bind is that the closure is in a very well-controlled environment and so doesn't close over things you don't want kept around.)
Now, I've never done any SVG programming with Prototype, so if observe doesn't work for some reason, you might try directly assigning to the onclick reflected property:
function myobject(svgShape) {
this.svgshape = svgshape;
this.svgshape.onclick = this.doSomething.bind(this);
}
myobject.prototype.doSomething = function() {
alert("works");
}
I'm still using bind there so that this has the correct value.
These posts from my anemic little blog offer more discussion of the above:
Mythical methods
You must remember this
Closures are not complicated

Ok, we can have private identifiers in javascript, but what about protected ones?

Simple as that, can we emulate the "protected" visibility in Javascript somehow?
Do this:
/* Note: Do not break/touch this object */
...code...
Or a bit of google found this on the first page:
http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html
Sure you can. Here's another example.
What could that possibly mean? You don't have classes.
I suppose you could analyze caller to determine whether it meets some set of criteria for being permitted to call a method. This will be hideously inefficient and your criteria will always be spoofable.
There's an interesting pattern worth mentioning here: a JavaScript contructor function may return any object (not necesserily this). One could create a constructor function, that returns a proxy object, that contains proxy methods to the "real" methods of the "real" instance object. This may sound complicated, but it is not; here is a code snippet:
var MyClass = function() {
var instanceObj = this;
var proxyObj = {
myPublicMethod: function() {
return instanceObj.myPublicMethod.apply(instanceObj, arguments);
}
}
return proxyObj;
};
MyClass.prototype = {
_myPrivateMethod: function() {
...
},
myPublicMethod: function() {
...
}
};
The nice thing is that the proxy creation can be automated, if we define a convention for naming the protected methods. I created a little library that does exactly this: http://idya.github.com/oolib/

Categories

Resources