Javascript cannot set property from a method invoked using this [duplicate] - javascript

This question already has answers here:
Javascript lost context when assigned to other variable
(4 answers)
Closed 4 years ago.
In the following Javascript code, the first call to saveResult from writeData succeeds while the second doesn't, please help.
class SimpleClass {
constructor() {
this.ir = "";
}
saveResult(res) {
console.log("entered save result")
this.ir = res;
console.log("value saved is " + this.ir);
console.log("end save result");
}
writeData() {
this.saveResult("abc"); //works fine
var sr = this.saveResult;
sr("abc"); //throws error -> Cannot set property 'ir' of undefined
}
} //end of class
function testLocally() {
var sc = new SimpleClass();
var wr = sc.writeData();
console.log("done");
}
testLocally();

A function gets is context based on how it is invoked. When you call it like
this.saveResult("abc"), this inside the function will refer to the this which called it, which in your case is the class context since you created an instance of class and invoked writeData method from the class instance causing the this inside writeData to refer to class context.
However when you run it like this:
var sr = this.saveResult;
sr("abc");
Although sr has the reference to the function, its called from the window context and hence it doesn't work correctly. You can call it using .call method and provide the context like this:
var sr = this.saveResult;
sr.call(this, "abc");

Related

Referring to Class instantiater in javascript [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have this method of a JavaScript class that I've created:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
newRule.sheet.deleteRule(i);
}
});
}
when you instantiate a class, it essentially has to be set to a variable, like so:
const newRule = new NewRule(*params*);
and the methods/properties of said class can refer to the class object using this. like so:
this.method();
this.property;
What I'd like to know is: how does one refer back to the variable that instantiated the class within a function that is called by a method of said class?
To be even clearer: a function that is called within a method of a class alters the scope, which also means it alters the definition of this.. My question is: how do you get around this? How could you access the variable that instantiated the class when you are out the of scope of the methods within said class?
As I was composing this question, I realized that you can set the this value for a .forEach loop like this:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
this.sheet.deleteRule(i);
}
}, this);
}
However, the way this code works is something that--as far as I know--is just a benefit of the .forEach method, and I'd still like to know how it should be handled in general.
Hopefully this should help you out, using your example.
class Rule {
constructor(rules) {
this.sheet = {
rules: rules || []
}
}
log(){
console.log('rules:',this.sheet.rules)
}
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
let self = this; // <-- here you can capture the instance
sheetRules.forEach(function(node, i) {
self.log() // <-- here you can use it in forEach
if (node.name != undefined)
this.sheet.deleteRule(i);
});
}
}
const fooRule = new Rule(['foo'])
const barRule = new Rule(['bar'])
fooRule.resetRule()
barRule.resetRule()
fooRule.log()
barRule.log()
Your forEach works because as you discovered, you passed this as an argument for the thisArg parameter. However, if you didn't, you could have just as easily set it to a variable in the outer scope and used it in the block scope.
Generally creating a variable called self or that and setting it to this is helpful, especially for arrow functions, which set this to the encapsulating scope and not the instance object.
You could make a temporary variable called self or something which would allow you to use both the object containing "this" instance as well as within that anonymous function passed to forEach, this which will refer to sheetRules when you don't specify another variable to use as this
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
let self = this;
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
self.sheet.deleteRule(i);
}
});
}
If I've not misunderstood you're looking for a way to retain your scope? You have a few options here.
The immediate answers would be to use Function.prototype.bind() or Function.prototype.call() to specify the context of this when invoking those methods.
Alternatively you could just make the scope of your this available where needed:
var MyClass = function () {
// Here we bind the local scope to a variable that will give us context where necessary.
// While it's not needed here, it can give context and set a pattern of reability through repitition.
var vm = this;
vm.methodA = function () {
// We continue to set our 'vm' pointer variable when needed.
var vm = this;
globalMethod.then(function () {
// We're able to retain context of our `this` through having scope of our 'vm' variable.
vm.methodB();
});
};
vm.methodB = function () {
console.log('I did stuff!');
};
};

How do I find the meaning of 'This' in following Javascript Code? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
What does this.radioStation refer to in the following code: does 'this.radiostaion' refer to Car or the function chagestation. Your input/ clarification would be appreciated. Any good rule of thumb to clear this up?
var Car = function () {
var gasolineLevel = 10;
function useGas (amt) {
if(gasolineLevel - amt < 0) {
console.log("out of gas :[");
} else {
gasolineLevel -= amt;
}
};
return {
radioStation: "104.5",
changeStation: function (station) {
this.radioStation = station;
},
go: function (speed) { useGas(speed); }
};
};
var Ferrari = Car();
console.log(Ferrari);
console.log(Ferrari.go(2));
console.log(Ferrari.go(10));
In changeStation, this will be whatever it was set to when calling changeStation. In normal functions, this is effectively a hidden argument that's determined by how the function is called.
In that specific example, you never call changeStation, so we can't tell you what this will be if/when you do.
If you called it like this:
var ferrari = Car();
ferrari.changeStation();
...then this would refer to the object created by Car (the one referenced by ferrari, created by the object initializer returned by Car at the end), because we called changeStation as part of a property accessor operation on ferrari.
But if you called it like this:
var ferrari = Car();
var changeStation = ferrari.changeStation;
changeStation();
then this would refer to the global object (in loose mode) or would be undefined (in strict mode).

What does "let _self = this" mean in Javascript/Typescript? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
What underlies this JavaScript idiom: var self = this?
(10 answers)
Closed 5 months ago.
In this code snippet, why is it that this.identifier doesn't work but _self.url works?
getConfig() {
let _self = this;
return function () {
this.page.url = this.url || window.location.href;
this.page.identifier = _self.identifier;
this.page.category_id = this.categoryId;
this.language = this.lang;
};
}
So does let _self = this actually do?
Functions have something called a context. A context is the object the function is being called on.
let person = {
name:"bill",
speak:function(){
console.log("hi i am "+this.name)
}
}
if you were to do person.speak()
it will be called on the object that was defined. The variable person is the context
so when you say this. it's the same as saying person.name
Now you can attach the function to something else.
var newperson = {name:'jill'}
newperson.speak = person.speak;
this will print hi i am jill when it's called.
Now on to step two.
GetConfig returns a function, however this function is not attached any object.
Check this out.
let person = {
name:"bill",
getSpeakFunction:function(){
return function(){
console.log('hi my name is '+this.name)
}
}
}
let func = person.getSpeakFunction()
Now the function func is all by himself.
Now when it is called who is this who the hell are you talking about.
That is what the function is thinking.
So we can help the function out by saying.
let person = {
name:"bill",
getSpeakFunction:function(){
let context = this; //listen hear function this is what i am talking about
return function(){
console.log('hi my name is '+context.name)
}
}
}
let func = person.getSpeakFunction()
this is special the language decides the value of this, however context is not. Context will be whatever is assigned to it. It will not change unless you the programmer changes it.
so using the word _self, context, $this
or anything else when you assign the value of this to it.
it is 'locked in place' like any other regular variable.
let a = 2;
//this will never change
let _self = this //_self will never change as it's your variable
Now when you call your function and it looks for _self. It knows exactly what you are talking about.
It takes the value of this (which is determined by how the function is called) and stores it in a variable (which is still accessible in the closure (that will have a different value of this when it is called) that getConfig is returning).

What difference between This and That [duplicate]

This question already has answers here:
What does 'var that = this;' mean in JavaScript?
(6 answers)
Closed 8 years ago.
I'd like to know and understand the different between this and that, and when I have to use it.
I ready many post and many tutorial but I don't understand yet
this is my class
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
console.log(this.member); // foo
console.log(that.member); // foo
return dec() ? that.member : null;
};
}
New
var myContainer = new Container('foo');
myContainer.service()
Calling myContainer.service() will return 'abc' the first three times it is called.
After that, it will return null
Why i have to do var that = this ??
this is a variable that gets the context of the current function (which depends on how it was called).
that has no special meaning. It is just a variable to which a value has been assigned.
In this particular case, that is assigned the value that this has while the Container is running, and is used inside the service function (but still has the value that is the context of the call to Container. Since service is a different function, its value of this could be different.
Normally, for this particular design of function, Container would be called as a constructor function (so this would be the instance object of Container) and then service would be called in the context of that instance object so you could use this instead of passing the value around via that. I have no idea why the author of that code chose to use that here.

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