Javascript conflict with 'this' reference [duplicate] - javascript

This question already has answers here:
javascript "this" points to Window object again
(2 answers)
Closed 6 years ago.
I have a piece of javascript code (using jQuery) that says:
$('.duration').each(function() {
$(this).html(this.duration_text);
});
It's iterating over each element of class 'duration' and setting the text as needed. The problem, is that the text it is setting is from a member variable, hence the this.duration_text. The 'this' reference is getting clobbered by the 'this' reference used by jQuery in the iteration.
How can I avoid this collision?
Although the underlying concept of the answer may be the exact same as the question this is marked as a duplicate of, it isn't immediately clear to me that this is the same question. In hindsight, sure, but while searching myself I didn't find it, nor was it clear it was the same question if I did find it.

You can create a reference to this before you create your loop, and then use self to refer to your object that has a property duration_text:
var self = this;
$('.duration').each(function() {
$(this).html(self.duration_text);
});
although you can just do:
$('.duration').html(this.duration_text);

You can use a closure variable to hold the reference to the outer object
var self = this;
$('.duration').each(function() {
$(this).html(self.duration_text);
});
But in the given snippet since you are assigning the same content to all duration elements, you can just use
$('.duration').html(this.duration_text);

Related

What is the value of this inside object literal??why pointing to window object? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
I am new to js and not able to understand which this does not points to the "obj" in the below code:
var obj = { x:this };
obj.x; // window object
I have referred many sites but all states the this always points to the object in whose context the method was called..does that not hold true for property??
Also why this pointing becomes correct inside a function as property of same object?? I have read that scope and context are not to be confused are different, then why only function is creating right context??I read that scope are of two type local and global then why context is affected.
Please explain in details, this question might be irrelevant maybe because i am still confused in scope and context..shares useful links too.

why can't I assign a property value to a following property in an object declaration? [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 8 years ago.
I'm learning Javascript and I've come across something I don't understand. This is the part of my object code:
var monster =
{
...
//is the animation starting?
hiding: true,
delayDuration: Math.floor(Math.random() * 60),
currentDelay: this.delayDuration,
...
};
If I console.log (delayDuration) I get a value, but if I console.log (currentDelay) it says 'undefined'.
I don't understand why currentDelay doesn't take the value of delayDuration.
Can someone please explain this?
edit: #Bergi why did you mark this as duplicate? I couldn't find my question answered somewhere else
edit2: yup, it's a duplicate. At least now I know the words for what I was asking.
At the point of object creation neither monster nor any of it's properties are defined. You can't use variable from the same object you're in the process of constructing.
Also, Javascript uses function scoping, which means that the value of this will either be the window object or will be scoped to the closest instance you're creating using new (or other instance creation techniques).

What is the point of prototypes in JavaScript? Why not add method directly to constructor? [duplicate]

This question already has answers here:
Declaring javascript object method in constructor function vs. in prototype [duplicate]
(3 answers)
Closed 9 years ago.
So I am going over a few lessons over JavaScript at CodeAcademy, and I ran into this section regarding prototypes.
A bit from the code:
function Dog(breed){
this.breed = breed;
};
Dog.prototype.bark = function(){
console.log("Bark!");
};
I don't understand the point of doing it that way. Why not just do it this way? (The way I first learned.)
function Dog(breed){
this.breed= breed;
this.bark = function(){
console.log("Bark!");
};
}
The second way, everything is together in one block, and not separated. What is the advantage of the first one? I know that there is, I'm just not seeing it.
One difference is, that in the prototype case the function exists only once and changing it will change all objects using this prototype. In the this. case the function is repeated in every object.
This makes a difference both in footprint and semantics.
it is for performance reasons. when creating a new instance of objects and calling a native method you are eating more memory for every creation.
On the other hand when using prototype it is more memory safe regardless the amount of Object created.

What is the reasoning behind declaring var that = this; in javascript? [duplicate]

This question already has answers here:
What does 'var that = this;' mean in JavaScript?
(6 answers)
Closed 9 years ago.
I came across this many times in a new code base that I'm looking at and was wondering is there is any proper reasoning behind it?
You can use var that = this; is order to keep a reference to current this object, when later this will be pointing to something else.
Example (taken from here):
$('#element').click(function(){
// this is a reference to the element clicked on
var that = this;
$('.elements').each(function(){
// this is a reference to the current element in the loop
// that is still a reference to the element clicked on
});
});
Sometimes the meaning of this in JavaScript changes based on the scope. this inside of a constructor means something different than this inside of a function. Here's a good article about it.
If you want access to "this" outside/inside of the scope of a specific function call where what "this" is may have changed. Just one example I can think of.

Why can't one set an alias to document.getElementById()? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript function aliasing doesn't seem to work
Set document.getElementById to variable
Code would be more efficient if this was possible:
var min = document.getElementById;
and then call document.getElementById() using min().
Not trying to write minified code but in this particular case one can reduce scope lookup and shorten some lines.
Is this a syntax issue or a limiation on the language?
When you call foo.bar() then this is set to foo inside bar
When you copy foo.bar to window.bar then call window.bar(), this is set to window.
getElementById has to operate on a DOM document object.

Categories

Resources