I have defined an API object:
function API() {
var self = this;
return {
getRandomArticle: function() {
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&exchars=50000&format=json&callback=?", function (data) {
for(var id in data.query.pages) {
console.log(data.query.pages[id].extract);
}
});
},
repeatAPICall: function() {
self.getRandomArticle();
console.log(self);
setTimeout(self.repeatAPICall, 5000);
}
}
}
And then I instantiated the API object with window.test = new API();.
When I head over to Chrome Dev tools and call window.test.repeatAPICall(), it works once, then it fails and says TypeError: Object #<API> has no method 'getRandomArticle'
I suspect that somehow the recursive call is behaving differently than I intended, what am I doing wrong?
Working code:
function API() {
var self = this;
self.getRandomArticle = function() {
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&exchars=50000&format=json&callback=?", function (data) {
for(var id in data.query.pages) {
console.log(data.query.pages[id].extract);
}
});
},
self.repeatAPICall = function() {
self.getRandomArticle();
console.log(self);
setTimeout(self.repeatAPICall, 5000);
}
return this;
}
window.test = new API();
Now you've fixed "self" vs. "this" the next change is to use
self.getRandomArticle= ...
self.repeatAPICall=...
and then just return self/this. That should work. Right now, you have two objects - this and the one you return.
Your main issue is the passing of this.repeatAPICall into setTimeout. When you call a method in JavaScript, the this keyword points to the object that called it:
var something = {
foo : function(){
return this;
}
};
something.foo(); //=> something
However, if you assign the function to a different variable, the context changes (to the global window object):
var something = {
foo : function(){
return this;
}
};
something.foo(); //=> something
var bar = something.foo;
bar(); //=> window
This is what's happening above; you're passing a reference to the function to setTimeout, which is then losing the correct context.
Instead, you need to pass in a function which keeps the context; you could use the self = this statement like so:
repeatAPICall: function() {
self = this;
self.getRandomArticle();
setTimeout(function(){
self.repeatAPICall();
}, 5000);
This creates anonymous function which remembers the state of the self object (this is how JavaScript variable scope works). When that function gets called, it can then call repeatAPICall as a method on that object, rather than as a function with no context.
The accepted answer avoids having to do this (each method can access self), but hopefully this explains why it wasn't working.
Related
I'm reading about ngInfiniteScroll, and i'm a newbie about JS.
As I've read the demo of nfInfiniteScroll, it's hard for me to understand why Reddit.nextPage have been transformed into Reddit.prototype.nextPage and it has been used the bind() method to wrap a part of Reddit.prototype.nextPage body.
Here is the code.
myApp.controller('DemoController', function($scope, Reddit) {
$scope.reddit = new Reddit();
});
// Reddit constructor function to encapsulate HTTP and pagination logic
myApp.factory('Reddit', function($http) {
var Reddit = function() {
this.items = [];
this.busy = false;
this.after = '';
};
Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
var url = "https://api.reddit.com/hot?after=" + this.after + "&jsonp=JSON_CALLBACK";
$http.jsonp(url).success(function(data) {
var items = data.data.children;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i].data);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
};
return Reddit;
});
I've just understood: by using this I can have access to properties in Reddit object.
Is it only because var Reddit is assigned an anonymous function and I need to bind this of the anonymous function to this of Reddit.nextPage, so they refer to the same properties?
But I can crearly see it is possible to have access to those properties even without the bind() method. See:
if (this.busy) return;
this.busy = true;
I've read some articles about the topic, but none exaplains it in depth: I'm really confused about.
Lets look at these functions:
Reddit.prototype.nextPage = function() {
// outer function
...
$http.jsonp(url).success(function(data) {
// inner function
}.bind(this));
};
Without binding, this in inner function would have different properties, since it's in another context. But if we call bind(this) we tell inner function to use this from outer function's context.
For more information I recommend this article.
I haven't visited the blog post, but I'm guessing that the reason it has been moved to be declared on the prototype is to have it automatically included in each instance of your "Reddit" service. Every time your service is created it will include this method, as all prototype methods are automatically inherited.
Regarding the bind, whenever you are passing a function as an argument, when the function is to get executed it will lose the main context, meaning it will not be bound to your Reddit service any more, because it will have a new scope of execution. Therefore calls to this.items, this.busy and this.after would all be undefined and would cause errors.
Here's some more info on the bind(), call() and apply().
this is context dependent. An example:
var foo = {
bar: function() {
console.log(this.baz);
},
baz: 3
};
foo.bar(); // logs 3
But in an asynchronous callback the context is gone, an example using setTimeout:
var foo = {
bar: function() {
setTimeout(function() { console.log(this.baz); }, 0);
},
baz: 3
};
foo.bar(); // logs undefined or throws an error in strict mode
'this' is no longer in the context of foo. We can get around that limitation using bind:
var foo = {
bar: function() {
setTimeout((function() { console.log(this.baz); }).bind(this), 0);
},
baz: 3
};
foo.bar(); // logs 3
We've now bound the context to foo (the value of this at the call site) which is what's going on in your example, the binding of this in the callback passed to the success handler of the promise returned by $http.jsonp.
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Explanation asked about the value of 'this' in Javascript [duplicate]
(2 answers)
Closed 8 years ago.
Simple question. Why do we have set that = this? If we dont, we are in the global scope...but why?
var myObj = {
specialFunction: function () {
},
anotherSpecialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
var that = this;
this.getAsyncData(function () {
// this now refers to global scope....why?
that.specialFunction();
that.anotherSpecialFunction();
});
}
};
myObj.render();
Writing that = this doesn't change the scope. The way the anonymous function is called will always end up with this being global object,* because that's exactly what the spec says should happen. Using that = this is just a workaround.
You could make this always point to myObj by using Function.call:
var myObj = {
specialFunction: function () {
},
getAsyncData: function (cb) {
cb.apply(this);
},
render: function () {
this.getAsyncData(function () {
this.specialFunction();
});
}
};
and/or using Function.bind:
var myObj = {
specialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
function callback() {
this.specialFunction();
}
this.getAsyncData(callback.bind(this));
}
};
* Unless you're in strict mode, in which case this is undefined.
take a look at the this keyword in JavaScript and how it works. I’m sure we’ve all come across this issue:
$("myLink").on("click", function() {
console.log(this); //points to myLink (as expected)
$.ajax({
//ajax set up
success: function() {
console.log(this); //points to the global object. Huh?
}
});
});
this is a variable that is automatically set for you when a function is invoked. The value it’s given depends on how a function is invoked. In JavaScript we have a few main ways of invoking functions. I wont talk about them all today, but just the three ways most people use them; either when a function is called as a method, or on it’s own, or as an event handler. Depending on how a function is invoked, this is set differently:
function foo() {
console.log(this); //global object
};
myapp = {};
myapp.foo = function() {
console.log(this); //points to myapp object
}
var link = document.getElementById("myId");
link.addEventListener("click", function() {
console.log(this); //points to link
}, false);
Doing $("myLink").on("click", function() {}) means that when the element is clicked, the function is fired. But this function is bound as an event handler, so this is set to the reference to the DOM element myLink. The success method you define within the Ajax request is just a regular function, and as such when it’s invoked, this is set to the global object, as it is when any function that’s not an event handler or an object method is.
$("myLink").on("click", function() {
console.log(this); //points to myLink (as expected)
var _this = this; //store reference
$.ajax({
//ajax set up
success: function() {
console.log(this); //points to the global object. Huh?
console.log(_this); //better!
}
});
});
Source: http://tinyurl.com/melbl92
EDIT: in JavaScript the "this" context depends on how your function is called, example:
function helloWorld()
{
console.log(this);
}
And here two ways to call this function:
new helloWorld(); note that if you call your function in this
way, the context of this will be the context of the function +
prototype, so your console will show this: helloWorld {}
helloWorld(); if you call your function without of the "new",
the context of "this" will be global(Window), so your console will show
this: Window about:home
Ok, with this little explanation i will try to explain now why you
have sometimes to use self/that...
Imagine that you want to use this.name inside this.hello function. Like I said before, the context of "this" depends on how your function is called, so if you want to ensure that this.name inside of this.hello function refer to this.name outside is recommended that you use self/that to avoid what happens bellow
function helloWorld(){
var self = this;//or that = this
this.name = "YourName"
this.hello = function(){
console.log(this); //the context of "this" here will be: "hello {}"
return this.name; //undefined, because you don't have name attribute inside hello function
}
new this.hello(); //note how hello is called here...
}
var test = new helloWorld();
And here a good explanation about context x scope:
http://ryanmorr.com/understanding-scope-and-context-in-javascript/
I have this Javascript constructor-
function TestEngine() {
this.id='Foo';
}
TestEngine.prototype.fooBar = function() {
this.id='bar';
return true;
}
TestEngine.prototype.start = function() {
this.fooBar();
}
TestEngine.prototype.startMethod = function() {
inter = setInterval(this.start, 200);
}
var test = new TestEngine();
test.startMethod();
Gives me this error -
Uncaught TypeError: Object [object global] has no method 'fooBar'
I tried console.log and found out that when I call this.start from within setInterval, this points to the window object. Why is this so?
The this pointer can point to one of many things depending upon the context:
In constructor functions (function calls preceded by new) this points to the newly created instance of the constructor.
When a function is called as a method of an object (e.g. obj.funct()) then the this pointer inside the function points to the object.
You can explicitly set what this points to by using call, apply or bind.
If none of the above then the this pointer points to the global object by default. In browsers this is the window object.
In your case you're calling this.start inside setInterval. Now consider this dummy implementation of setInterval:
function setInterval(funct, delay) {
// native code
}
It's important to understand that start is not being called as this.start. It's being called as funct. It's like doing something like this:
var funct = this.start;
funct();
Now both these functions would normally execute the same, but there's one tiny problem - the this pointer points to the global object in the second case while it points to the current this in the first.
An important distinction to make is that we're talking about the this pointer inside start. Consider:
this.start(); // this inside start points to this
var funct = this.start;
funct(); // this inside funct (start) point to window
This is not a bug. This is the way JavaScript works. When you call a function as a method of an object (see my second point above) the this pointer inside the function points to that object.
In the second case since funct is not being called as a method of an object the fourth rule is applied by default. Hence this points to window.
You can solve this problem by binding start to the current this pointer and then passing it to setInterval as follows:
setInterval(this.start.bind(this), 200);
That's it. Hope this explanation helped you understand a little bit more about the awesomeness of JavaScript.
Here is a neat way to do OOP with javascript:
//Global Namespace:
var MyNamespace = MyNamespace || {};
//Classes:
MyNamespace.MyObject = function () {
this.PublicVar = 'public'; //Public variable
var _privatVar = 'private'; //Private variable
//Public methods:
this.PublicMethod = function () {
}
//Private methods:
function PrivateMethod() {
}
}
//USAGE EXAMPLE:
var myObj = new MyNamespace.MyObject();
myObj.PublicMethod();
This way you encapsulate your methods and variables into a namespace/class to make it much easier use and maintain.
Therefore you could write your code like this:
var MyNamespace = MyNamespace || {};
//Class: TestEngine
MyNamespace.TestEngine = function () {
this.ID = null;
var _inter = null;
//Public methods:
this.StartMethod = function (id) {
this.ID = id;
_inter = setInterval(Start, 1000);
}
//Private methods:
function Start() {
FooBar();
console.log(this.ID);
}
function FooBar() {
this.ID = 'bar';
return true;
}
}
//USAGE EXAMPLE:
var testEngine = new MyNamespace.TestEngine();
testEngine.StartMethod('Foo');
console.log(testEngine.ID);
Initially, the ID is set to 'Foo'
After 1 second the ID is set to 'bar'
Notice all variables and methods are encapsulated inside the TestEngine class.
Try this:
function TestEngine() {
this.id='Foo';
}
TestEngine.prototype.fooBar = function() {
this.id='bar';
return true;
}
TestEngine.prototype.start = function() {
this.fooBar();
}
TestEngine.prototype.startMethod = function() {
var self = this;
var inter = setInterval(function() {
self.start();
}, 200);
}
var test = new TestEngine();
test.startMethod();
setInterval calls start function with window context. It means when start gets executed, this inside start function points to window object. And window object don't have any method called fooBar & you get the error.
Anonymous function approach:
It is a good practice to pass anonymous function to setInterval and call your function from it. This will be useful if your function makes use of this.
What I did is, created a temp variable self & assigned this to it when it is pointing your TestEngine instance & calling self.start() function with it.
Now inside start function, this will be pointing to your testInstance & everything will work as expected.
Bind approach:
Bind will make your life easier & also increase readability of your code.
TestEngine.prototype.startMethod = function() {
setInterval(this.start.bind(this), 200);
}
Typically, calling this would work; but I am calling the method in another context, so this refers to that context rather than the 'parent' object.
Here's the code:
var someConfig = {
things: [
{
attr1: 'foo',
attr2: 'bar',
action: function() {
console.log(this);
}
}
]
}
function Constructor(config) {
var self = this;
self.name = 'test';
self.things = config.things;
$.each(self.things, function(i, thing) {
thing.action();
});
}
var obj = new Constructor(someConfig);
console.log(obj);
Here's a jsfiddle. The goal is to have both objects that are in the console to be the same, but this in the context of the action method returns the original object to which action belongs, rather than the constructor.
The only thing I can think of is to pass self into action, but I think there's a better way.
Firstly, a couple of points about your code. your config property is uniqueAction yet later you refer to it as config.action. When you call obj.action you need to call it as a function like: obj.action();
With that in mind, the following seems to do what you require...
var config = {
action: function() {
console.log(this.name);//<- IMPORTANT PART
}
}
function Constructor(config) {
var self = this;
self.name = 'test';
self.action = config.action;
}
var obj = new Constructor(config)
obj.action();
Notice that the console.log call now uses this.name instead of self.name.
Here is a working example
The only way I see is to tack the 'constructor' onto the config thing before calling the action.
Check out this Fiddle, which was forked off yours.
I've changed two things:
First, the action function no longer references this, but rather the property parent of this.
action: function() {
console.log(this.parent);
// ^^^^^^^
}
Second, each thing object receives a parent property, which references self.
$.each(self.things, function(i, thing) {
thing.parent = self;
thing.action();
});
Can functions passed into constructors have access to the constructor's other properties?
Yes, but only if you pass that object to the function (or implicitly use the this keyword).
What you did try was accessing the local self variable from a function that was declared outside the constructor, which is just impossible.
So just use
{
action: function() {
console.log(this.name);
// ^^^^
}
}
And when calling obj.action() the this will point to the instance.
Okay, I'm hating Javascript right now, and I hope someone can help me.
I have code which is set up like the following:
function Obj1() {
var me = this;
this.something = "yay";
this.getThis = function(){
return me;
}
}
Obj1.prototype.method = function() {
return this.something;
};
function Obj2() {
this.something = "nay";
}
Obj2.prototype.method = function() {
return this.something;
};
var o1 = new Obj1();
var o2 = new Obj2();
document.write(o1.method()); // Returns yay
document.write(o1.method.call(o2)); // Returns nay, but I need "yay" here
(JSFiddle # http://jsfiddle.net/A9u9K/)
My Problem is, that I need to call Obj1.method in the second case, but I am absolutely unable to get a reference to the object :(
How can I work around this?
Edit: Sorry, I got my example code pretty wrong :( Updated it. I took most of the code from a previous answer, because it is much nicer and still illustrates my problem.
Updated Answer:
document.write(o1.method.call(o2)); // Returns nay, but I need "yay" here
You've said you've got it sorted now, but as the answer to that isn't actually shown here on SO, I figured I may as well update to show it.
If it's method you want to have access me, even if it's been called with a different this value, you have to define it like getThis, as a closure over me:
function Obj1() {
var me = this;
this.something = "yay";
this.method = function() {
return me.something;
};
this.getThis = function(){
return me;
};
}
function Obj2() {
this.something = "nay";
}
Obj2.prototype.method = function() {
return this.something;
};
...or of course, if you don't need the "something" to be a property on the object, just make it a var within the constructor (a private variable, like me):
function Obj1() {
var me = this;
var something = "yay";
this.method = function() {
return something;
};
this.getThis = function(){
return me;
};
}
function Obj2() {
this.something = "nay";
}
Obj2.prototype.method = function() {
return this.something;
};
Original Answer: (To Revision 1 of the question, which didn't have me.)
but I thought that, when creating a closure (as I do in 4) Javascript should preserve "this".
this is set entirely by how a function is called, not where it's defined; more about that here and here. But the way you've defined your getThis function, you can use the fact it closes over the constructor call to solve this (no pun) without using this:
function Obj1() {
var me = this; // <== Use a variable to remember `this`
this.something = "yay";
this.method = function() {
return this.something;
};
this.getThis = function(){
return me; // <== Return it
};
}
Live example
More about closures and the plumbing that makes the me thing work here.
There is a cost involved in this, and just generally in your pattern of defining functions within the constructor function: Each individual object created by Obj1 and Obj2 gets its own copy of each function. This can have memory implications if there are lots of these objects running around (but unless you have lots, you needn't worry and you get benefits like the me thing and other private variables). In constrast, if you use a function assigned to the prototype, all instances will share a single, common copy of the function.
In your sample code, only the getThis function really needs to be duplicated for every instance (because you're relying on the closure), so you can do this to avoid unnecessary function proliferation:
function Obj1() {
var me = this;
this.something = "yay";
this.getThis = function(){
return me;
};
}
Obj1.prototype.method = function() {
return this.something;
};
function Obj2() {
this.something = "nay";
}
Obj2.prototype.method = function() {
return this.something;
};
see it here http://jsfiddle.net/2Jhwv/5/
The issue is with the reference changing for the this object with scope.
Instead if using a this directly in closure use a local variable equated to this, i.e, change your Obj1 toL
function Obj1() {
this.something = "yay";
var that = this;
this.method = function() {
return that.something;
}
this.getThis = function(){
return that;
}
}
The only way to solve this is to another place holder to hold the value of this in Obj1 and use it in the function method() and getThis().
function Obj1() {
var instance = this;
this.something = "yay";
this.method = function() {
return instance.something;
}
this.getThis = function(){
return instance;
}
}
But what I cannot under stand is why you are doing it(obj1.getThis.call(obj2).method())?
This explicitly says that you want to change the scope of the method getThis() to something else, then you are trying to solve the problem which was created by this usage.
Can you tell why you want something like this?