This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I've created a simple pointer to a method like so:
export class SmbwaService {
getExistingArsByLab(labId: number): Observable<SmwbaAr[]> {
this.otherMethod();
}
otherMethod(): void {
}
}
let method: (x: number) => Observable<SmbwaAr[]>;
method = this.service.getExistingArsByLab;
method(12);
That executes OK insofar as it does call getExistingArsByLab method. However, I then get an error when it tries to call otherMethod because:
Cannot read property otherMethod of undefined.
What's the right way to do this? Obviously in my actual code method is being set to one of a number of different methods based on some conditions.
Use Function.bind to obtain a function reference that's bound to a particular value of this:
method = this.service.getExistingArsByLab.bind(this.service)
method(2)
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:
Add method to string class
(6 answers)
Closed 4 years ago.
So, for learning purposes I'd like to recreate the "charAt()" existing method in Javascript which tells you the position of a character in a given string. I'll call the method "CharAtX"
To do so, I've created a function with 2 parameters : The first one is the word, the second is the position, here is the code I have :
function charAtX(word,pos) {
word_split = word.split("");
return(word_split[pos])
}
console.log(charAtX("Truck",2))
So, it obviously works, if i call charAtX("truck",2), i will have "u" returned.
But my question is the following :
The original charAt can be called like such
my_word.charAt(3)
Mine can't though. Why is that and how could I change my function into a method so that I can?
You have to call charAtx function in the context of String object.So, When you call string.charAtx, this object refers to the string. You have to learn prototype and this object in jvascript.
String.prototype.charAtX = function(pos) {
word_split = this.split("");
return(word_split[pos])
}
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
i have JS class that has method like this:
setupComponent() {
document.getElementById("message-input").addEventListener("keydown", this._onKeyPress);
document.getElementById("send-button").addEventListener("click", this._onSend);
}
Right under it, there are two methods:
_onKeyPress(event) {
if (event.code === "Enter") {
this._onSend();
}
}
_onSend() {
console.log("send");
}
My question is: why direct call from "click" eventListener works (it logs message), and this._onSend() method, called in _onKeyPress returns this._onSend is not a function.
Also using this._onSend() inside setupComponent() works.
Is this some kind of magic associated with eventListeners?
When a function is used as an event handler, its this is set to the element the event fired from this - JavaScript | MDN. So you cant expect your methods to be there, but you can bind your this to your function using Function.prototype.bind().
document.getElementById("message-input")
.addEventListener("keydown", this._onKeyPress.bind(this));
This question already has answers here:
Javascript dynamically invoke object method from string
(5 answers)
Closed 8 years ago.
I want to use a method in which i will pass a function_name as parameter to another function.
On the other function, the parameter will be treated as a function
here's my code example
<div class="btn_crt_acct" onclick="toggle_object('register_div','slideDown');">
CREATE AN ACCOUNT
</div>
whch will call a function like this
function toggle_object(obj,fun)
{
$('#'+obj).fun('slow');
// fun => slideDown
// so $('#'+obj).fun('slow'); => $('#'+obj).slideDown('slow');
}
but i am doing something wrong as it states an error in console, $fun(..) is not a function.
How can i make it work perfectly??
Thanks
You'd do that with bracket notation
$('#'+obj)[fun]('slow');
FIDDLE
But why not use a proper event handler, and slideToggle if you intend to toggle it
$('.btn_crt_acct').on('click', function() {
$('#register_div').slideToggle();
});
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
Alright, so I have two classes.
Class 1 contains a specific function, which accesses some of the class' properties. This is what it looks like:
function class1() {
this.variable = "something";
}
class1.prototype.callback = function() {
console.log(this.variable); // Returns undefined
}
Class 2 can call any function it is given, and looks like this:
function class2() {}
class2.prototype.caller = function(callback) {
callback();
}
Then in my regular Javascript I do this:
var c1 = new class1();
var c2 = new class2();
c2.caller(c1.callback);
It is supposed to return "something", however it throws an undefined error. I know it is because it is in the scope of class2 and it is trying to access the variable there, however I have no idea how to get it to execute within the scope of class1.
Any help is greatly appreciated!
Use .bind() or a wrapper function:
c2.caller(c1.callback.bind(c1));
Note that your code was wrong in that it called the function before passing in the return value.
Alternatively:
c2.caller(function() { c1.callback(); });