jQuery overwriting 'this' in prototype [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
jQuery - trigger not produce the expected result
(1 answer)
Closed 7 years ago.
I have declared a JavaScript object:
function A(name){
this.name=name
}
A.prototype.test=function(){
console.log(this.name);
};
as a simple example I have set up a button that if it's clicked should output a variable to the local console log:
<button id='test'>test</button>
the script:
var t=new A('hello');
$('#test').click(t.test);
when I click the button I want this.name to show (in this case 'hello'), but instead this refers to the clicked button, and not to the object I created.
this is a debugging script of course. In real life I'm binding a function to the window.resize event which will re-build a window on resizing.
There is a JSFiddle that shows the problem.
I have one solution for this, that is declaring the resize (or click function) in the constructor of the object and using an alternative name for this, like so (Here's the JSFiddle):
function A(name){
this.name=name
var self=this;
$("#test").click(function(){
console.log(self.name);
});
}
but I'd rather use a prototype and bind the function in the object's constructor. How can I do this using prototypes?

You can use bind, which will set the value of this ahead of time:
var t=new A('hello');
$('#test').click(t.test.bind(t));

Related

Javascript Behavior when Function.prototype.bind is called serially [duplicate]

This question already has answers here:
Can you rebind a rebound function using `bind`
(3 answers)
How to override 'this' parameter of a bound function in javascript
(3 answers)
Javascript function bind override (how to bind it to another object)
(2 answers)
Closed 4 months ago.
I have a question about Function.prototype.bind.
function f() {
return this;
}
const g=f.bind({foo:'foo'});
const h=g.bind({bar:'bar'});
console.log(h()); // expected {bar:'bar'} but get {foo:'foo'}
I was expecting the above snippet to produce either {foo,bar} or {bar} but instead I get {foo}.
Can you explain what is going on?
Using .bind() to create a function that "fixes" the value of this in the called function results in a function where this cannot be overridden.
What you get back from .bind() is a new function that will pass along arguments to the original target function, with a guarantee that in that called function the value of this will be what you ask for. Re-binding that function therefore does no good: you do get back a new function, but it calls a function (the first bound function) that explicitly ignores its own this value.

Can anyone tell me the difference between function defined in function and adding function using prototype [duplicate]

This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 4 years ago.
I am trying to differentiate between first block and second block of code.
//first block
function xyz(){
this.callXyz=function(){
console.log('callXyz inner');
}
}
// second block
xyz.prototype.callXyz=function(){
console.log('prototype function');
}
I'm going to guess that your first code block was meant to look like this:
function xyz(){
this.callXyz = function(){
console.log('callXyz inner');
}
}
And I'm going to assume you do new xyz at some point to create an instance.
If so, the difference is that in that first example, a new function is created each time xyz is called (presumably via new) and assigned as an own property on the new object. In the second example, the function is only created once, and then the new object created by new xyz gets that property as an inherited property from its prototype; all of the instances created via new xyz share the same function.

What does `bind(this)` mean? [duplicate]

This question already has answers here:
What is the use of the JavaScript 'bind' method?
(23 answers)
Closed 6 years ago.
In some part of onInit function of a controller in a SAPUI5 application there is an auto generated code like this:
this.getView().addEventDelegate({
onBeforeFirstShow: function() {
// Some codes
}.bind(this)
});
Now my question is what does .bind(this) mean? What does it do? Is it a pure JavaScript code or it is related to SAPUI5?
Yes, it's pure JavaScript code, you can learn more about what bind is and does here
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.
In this case what it does is basically binding the current this to that function, so when onBeforeFirstShow is called, the this inside that function will be the one passed to the bind function.
You may also want to look at the new arrow function syntax in ES6, it auto binds the current this so bind(this) is not necessary.
It binds the listener of the function to the current class, then when you use this pointer inside of the onBeforeFirstShow function, the this pointer refer to encapsulated class and you can access to its members.
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.
Syntax
fun.bind(thisArg[, arg1[, arg2[, ...]]])
Reference to Mozilla Developer Network

Where is a function's this value stored? [duplicate]

This question already has an answer here:
How to inspect a JavaScript Bound Function
(1 answer)
Closed 6 years ago.
I know that you can bind the this value of a function using
function.bind(new_this_value, arguments)
But is there a way to access the bound value? ie something like this:
console.log(my_function.boundValue)
In other words, suppose a module provides the following function:
function getACoolFunction () {
var someFarAwayFunction = function() {console.log(this.name)}
var bound_this_value = {name: "bound this value"}
someFarAwayFunction.bind(bound_this_value)
return someFarAwayFunction;
}
and I have this in my code:
import {getACoolFunction} from coolModule
var coolFunction = getACoolFunction();
// coolFunction.bound_value
How do I get the bound value of coolFunction from my code without changing the module?
Nothing prevents you from doing this:
let my_function = function.bind(new_this_value, arguments);
my_function.boundValue = new_this_value;
As from the standard, a bound function is:
an exotic object that wraps another function object.
It has internal properties containing original function, provided this and arguments.
As they are explicitly mentioned as internal, I would say that they are not directly exposed and accessible.
Probably this Q/A contains details that can help you to work around this limitation.

typescript window.setInterval() not working properly [duplicate]

This question already has answers here:
Referencing "this" inside setInterval/setTimeout within object prototype methods [duplicate]
(2 answers)
Closed 6 years ago.
I'm having issues with the window.setInterval() method. Below is an example of the structure, the method "repeat" is called repeatedly, however I cannot call any methods inside "repeat". In the example when I instantiate manager (let m = new manager()) it will print "Before Print", but will not print out the log from the printStuff method, or the "After Print" message.
Does anyone know why this is happening? Obviously this isn't my actual code as it's simple enough to not be in separate functions, however my actual code needs to call many functions in the "repeat" function and it will stop execution when it finds a call to another function.
class manager{
constructor(){
window.setInterval(this.repeat, 5000);
}
repeat(){
console.log("Before Print");
this.printStuff();
console.log("After Print");
}
printStuff(){
console.log("Print Stuff");
}
Set interval will take take the this.repeat out of the context you need to either explicitly 'bind' the method using
setInterval(this.repeat.bind(this), 5000)
or
setInterval(()=>this.repeat(), 5000)

Categories

Resources