How to pass "this" to another object in javascript? [duplicate] - javascript

This question already has answers here:
How do I pass the this context to a function?
(5 answers)
Closed 8 years ago.
how to pass "this" to another function ???
function demo1()
{
demo2(this);
}
how to get this object of demo1 into demo2 ???
function demo2()
{
//how to get this object of demo1 into demo2 ???
}

You can do this a number of ways.
Pass it in
You're already doing this, sort of.
function demo1()
{
demo2(this);
}
function demo2(demo1)
{
console.log(demo1);
}
Call it in the current scope
function demo1()
{
// Executes demo2 in scope of demo1
demo2.call(this);
}
function demo2()
{
console.log(this);
}

function demo1()
{
demo2(this);
}
function demo2(data)
{
console.log(data);
}
Check out the details on console.

That's quite easy to do. You can use .call or .apply:
demo2.call(this);
The first argument you provide will be the context (this) used during execution.

Related

Javascript "this" not set in function that was passed around [duplicate]

This question already has answers here:
"This" within es6 class method [duplicate]
(1 answer)
How to access the correct `this` inside a callback
(13 answers)
Closed last month.
I have a class, in where I have a method that creates a function to be called by some third party library. Inside the function I want to call class members, but the "this" keyword is not set anymore at the moment the function is called. How can I get the this keyword to work inside the function?
I have an oversimplified example:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) { this.printIt(x); };
}
}
(new myclass).getFunc()("test");
TypeError: Cannot read properties of undefined (reading 'printIt')
And I also have a solution which I am not happy with, and which I expect can be done in a more elegant way:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
let self = this;
return function(x) { self.printIt(x); };
}
}
(new myclass).getFunc()("test");
class myclass {
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) {
this.printIt(x);
}.bind(this);
}
}
(new myclass).getFunc()("test");

How to reference a sub function from within a function by its name as a string [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 2 years ago.
Can anyone tell me what I can replace the evil eval with in this code?
var x = function(funcName) {
function funcA () {
console.log("a");
}
function funcB () {
console.log("b");
}
var funcToRun = eval(funcName);
return funcToRun();
};
x("funcA");
x("funcB");
I've see a bunch of different solutions, but none seem to fit this scenario. Essentially, I need to be able to pass a string into a function as a "config" of which sub-function to run. I don't have access to the code that calls x, I've just been instructed that only primitive and string values can be configured in the call.
P.S. This is a super simplified version of the actual function.
Thanks!
James
You could just create an object and add those functions as properties that you can then access with a string.
var x = function(funcName) {
function funcA() {
console.log("a");
}
function funcB() {
console.log("b");
}
const fs = {
funcA,
funcB
}
var funcToRun = fs[funcName]
return funcToRun();
};
x("funcA");
x("funcB");

JavaScript field access from anonymous function [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
how can I access a fiel from within an anonymous function inside a method?
like in this example:
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
this will result in an error that "this" is undefined.
thank you very much in advance, I could not find an answer in the web after searching for hours.
best,
lev
In your anonymous function, this is bound to the function; it no longer refers to the class.
Use an arrow function instead, which doesn't have it's own this binding.
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
new Something().doSomething();
Alternatively, you could use something like .call(), .apply(), or .bind():
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function() {
console.log(this.gax);
}).call(this);
}
}
new Something().doSomething();
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function () {
console.log(this.gax);
}).apply(this);
}
}
new Something().doSomething();
You can use apply method. The apply() method calls a function with a given this value

Accessing a class method from with function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I'm simply trying to access a class method from within a function within another class method so:
class test
{
show()
{
setTimeout(function()
{
this.showInside()
},0)
}
showInside()
{
alert("WORKING")
}
}
var test2 = new test();
test2.show()
I'm obviously doing something wrong, and clearly I can't use this.showInside() within that function, but I can't figure out what I need to do...
Any help?
this depends on the context. Inside setTimeout, this doesn't refer to the instance. Here's a working example :
class test
{
constructor(){};
show(){
setTimeout((function(){ this.showInside() }).bind(this),0)
}
showInside(){
alert("WORKING");
}
}
var test2 = new test();
test2.show();

The 'this' keyword in a function [duplicate]

This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!
Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)
The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.
Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);

Categories

Resources