This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 5 years ago.
Im reading through the YDKJS books and I thought I understood lexical this for the most part.
However there is a section with code that shows this:
var obj = {
id: "awesome",
cool: function coolFn() {
console.log( this.id );
}
};
var id = "not awesome";
obj.cool(); // awesome
setTimeout( obj.cool, 100 ); // not awesome
Ok so the first obj.cool() makes sense of course....but why is the setTimeout printing not awesome.....I mean it's still calling obj.cool() which this refers to it's own objects id?
Or does setTimeout get called as another function that calls obj.cool()? but even in that case (Which I tried calling obj.cool() inside another function that also had an id property and it still printed the right one......so why would the this change with setTimeout?
Since the OBJ.COOL function is passed by reference, you are not actually passing the context object with it. The function gets new invocation context and executes on the WINDOW object, which now has a property called ID which was defined earlier.
Related
This question already has an answer here:
How to inspect a JavaScript Bound Function
(1 answer)
Closed 2 years ago.
Given a function,
function main() {
// some logic
}
Lets assume the function main is bind with const obj = { name: "John Doe" }
like const fn = main.bind(obj);
Now the question is, Is there a way to get the fn function binding?
Note: i know binding can be accessed using the this keyword inside the main function but is there any way to access this value outside the context. is there any magic (hypothetical) method like fn.getContext().
Thank you for your time.
No there is not. While the new function object has an internal [[BoundThis]] slot, that slot is not accessible via a user-facing API.
This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.
This question already has answers here:
Pass correct "this" context to setTimeout callback?
(6 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
Here's working code sample:
function Drum(){
this.noise = 'boom';
this.duration = 1000;
this.goBoom = function(){console.log(this.noise)};
}
var drum = new Drum();
setInterval(drum.goBoom.bind(drum), drum.duration);
If I remove .bind(drum) part from this code instead of 'boom' I'll get 'undefined' in console.
What's the reason of such behavior since typeof drum.goBoom returns 'function' ?
since typeof drum.goBoom returns 'function'
This is actually irrelevant. It's value of this keyword which is important in here. You are passing a function reference by passing drum.goBoom as the first argument of the setInterval function, without using bind for setting the this keyword's value manually the setInterval calls the function with global object as it's this value (context) which doesn't have noise keyword, so console.log logs undefined.
Taking a look at the documentation for bind.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
If you omit the bind(drum) then this within the call back will be something other than the drum object you want.
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
In java script when we make a new constructor function we use "this.property name". We use "this" to refer the object which currently in use. But in a general function we doesn't use "this" keyword. According to my understanding if we use "this" in function it should point to the current function. However when we used, it was not producing the expected result. Why? Example
function greet(name){ console.log("Hello " + this.name);
}
Output is "Hello" then blank.
Because in general function, we are by default referring 'window' object so anything we make it becomes window level object or variable.
Like,
function fun(){
this.title = "window";
}
fun();
or window.fun(); //both are same. Since we call window.fun, this.title means window.fun.
If you create like this:
var obj = {
}
**Now to make title at obj level, you can do like this:
fun.call(obj);
Now you can call obj.title.**
Read this about this
In most cases, the value of this is determined by how a function is called.
When you use the new keyword in javascript an implicit object is created and returned from the function call. Inside of the function this refers to the newly created object. Calling a function without new does not have the same behavior.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
My problem is as simple as the title.. I have some code which makes an AJAX call. This code is similar to this (JSFiddle):
function Test() {
this.name = "U don't wanna know my name..";
}
Test.prototype.ajax = function() {
$.ajax("url/path", data, function() {
alert(this.name);
});
};
var test = new Test();
test.ajax();
In this case this is undefined. I could place the following code before the ajax call and use that in stead of this:
var diz = this;
I was wondering if there's another way of using this without creating a new variable for it.
In this case this is undefined.
this.name is undefined (assuming you meant that), because this is specific to a function's context. Inside that ajax's callback handler this no more belonged to Test, it belonged to that callback function.
was wondering if there's another way of using this without creating a
new variable for it.
I don't think that without saving the reference to parent's this (Test's this) you can access this that belonged to a more global scope from a function's scope.