How to call JavaScript class's method from another method? [duplicate] - javascript

This question already has answers here:
'this' keyword overriden in JavaScript class when handling jQuery events
(2 answers)
es6 classes and "this" with event handlers [duplicate]
(2 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I am using iOS's JavaScriptCore framework but I am having difficulty getting a JavaScript (es6) class to call another method. Here is my playground code.
do {
let j = JSContext()!
j.evaluateScript("class Base123 { method1(arg1) { return this.method2(arg1) } method2(arg1) { return {\"asdf\":\"123\"} } }")
j.evaluateScript("var b = new Base123(); var handler = b.method1")
j.evaluateScript("handler(4)")?.toDictionary() //<-- expected ["asdf": "123"]
}
Essentially I am Creating a class called Base123 with two methods. method1 calls method2. However the call to method2 is undefined.
Does anyone know how to do this?
Reformatting the class definition to make it easier to read:
class Base123 {
method1(arg1) {
return this.method2(arg1)
}
method2(arg1) {
return {"asdf":"123"}
}
}
Is there something wrong with this javascript definition?

Try replacing var handler = b.method1 with var handler = b.method1.bind(b).

Related

How to access the correct `this` inside a nested class method callback [duplicate]

This question already has answers here:
when calling class method by reference, how to have "this" still point to that class? [duplicate]
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
Consider the below:
class foo(){
constructor(){this.x = 10}
f(){console.log(this.x)}
}
myfoo = new foo()
class bar{
constructor()
b(func){func()}
}
mybar = new bar()
mybar.b(myfoo.f())
Because of how this works in JavaScript, "this" in myfoo.f points to mybar instead of myfoo. How do I go around this? Also, why does JavaScript do this?
Response to duplicate
Before reporting this as a duplicate again, please note that this question is directed to the JavaScript class, not functions in this link. I don't think that link does not resolve my issue.

How to use a local variable in javascript function [duplicate]

This question already has answers here:
Javascript: Object Literal reference in own key's function instead of 'this'
(5 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Apologies if the terminology is off - javascript isn't my thing.
I have a function:
var input = {
getVal: function () {
return $(this).attr("data-current-val");
},
setVal: function () {
$(this).attr("data-current-val", $(this).val());
},
valHasChanged: function () {
return $(this).val() !== $(this).attr("data-current-val");
}
};
As you can see there is some repetition. Firstly, I repeat the data attribute name several times; secondly, I select a jquery object numerous times.
I've tried to remove the repetition. For instance, in respect of the data attribute, by adding node: "data-current-val" at the top and then calling it with this.node in place of the string. That causes an error, as does trying to define and then use the jquery objectin the same way.
Similarly part of the boolean in valHasChanged $(this).attr("data-current-val"), logically could be replaced by this.getVal but that doesn't seem to work either. Where am I going wrong?!
Any help appreciated.

javascript class.method1.method2 [duplicate]

This question already has answers here:
How does basic object/function chaining work in javascript?
(5 answers)
Chaining methods with javascript
(3 answers)
Closed 1 year ago.
i'm looking for something like :
document.getElementById("id").innerText.toString().length;
so : class.method1().method2().method3();
my code :
class Example
{
method1(){ .. }
method2(){ .. }
method3(){ .. }
}
from out class :
var element = new Example();
element.method1(); //works fine
element.method1().method2(); // error: method2 is not defined
any solution?
thanks for all :)
What you're looking for is known as a fluent interface. To implement this, just add return this; to the end of every method in the class.
Side note: document.getElementById("id").innerText.toString().length; is not a fluent interface - each function/attr returns a different value.

.bind not working with es6 class instance [duplicate]

This question already has answers here:
Can you bind 'this' in an arrow function?
(14 answers)
Closed 2 years ago.
using the bind documentation, if i replace the object (defined as module in their example), with an es6 class instance, it does not bind.
here are the docs...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
and here is my code...
class Foo {}
let foo = new Foo()
let fooVar = 'foo var'
let fooFunc = () => {
return this.var
}
foo['var'] = fooVar
fooFunc.bind(foo)
foo['func'] = fooFunc
// i expected this to return 'foo var', but instead get 'undefined'
foo.func()
how can i essentially add an instance method to an existing instance, and have it bind properly?
If you read the documentation about arrow function you will see that:
Does not have its own bindings to this or super, and should not be used as methods.
Therefore you cant bind a new this if it doesnt have one

Event handler function as a method [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 6 years ago.
I am very new to OOP and attempting my first project with it. Here is my question:
var calculator = {
operationBar: document.getElementById('operation-bar'),
print: function(){
this.operationBar.innerHTML += 1;
}
}
var one = document.getElementById('number1');
one.addEventListener('click',calculator.print)
When I click on my HTML element with the id (number1) I get the following error:
Cannot read property 'innerHTML' of undefined.
It is not relating the this keyword to my calculator object.
However if I do this:
var calculator = {
operationBar: document.getElementById('operation-bar'),
print: function(num){
this.operationBar.innerHTML += 1;
}
}
calculator.print()
It works and the this keyword seems to be working correctly.
The reason I know the problem is with the this keyword is because if I perform the function in the first snippet and replace this with calculator then it will work, as my event handler function as well.
Why is it behaving this way?

Categories

Resources