Reputation: 688
Please take a look at the following JS snippet:
var MyClass = function() {
var logging = true;
this.myFunction = function(logging) {
}
}
myObj = new MyClass();
myObj.myFunction(false);
Is there a way to access both logging variables within myFunction?
The only solution I could come up with (this.logging) does not seem to work: https://jsfiddle.net/x7m3w3gp/
Upvotes: 0
Views: 39
Reputation: 805
This should work;
var MyClass = function() {
this.logging = true;
var logging = 0;
this.myFunction = function(logging) {
var console = document.getElementById('console');
console.innerHTML = 'logging: ' + logging + '<br />';
console.innerHTML += 'this.logging: ' + this.logging + '<br/>';
console.innerHTML += 'var loggin:' + logging + ' !!! <br/>--> var logging scope never access';
}
}
myObj = new MyClass();
myObj.myFunction(false);
https://jsfiddle.net/x7m3w3gp/2/
Upvotes: 0
Reputation: 700232
From the code in the myFunction
method it's not possible to access the local variable from the scope outside it, as the parameter is shadowing the variable.
Using this.logging
doesn't access the variable, it would access a property of the object by the same name.
You can put a function in that scope that can access the variable, to use as a bridge from the myFunction
method.
Example of the variable, property and bridge usage:
var MyClass = function() {
// local variable
var logging = true;
// property
this.logging = 1;
// bridge local variable
function getLogging() { return logging; }
this.myFunction = function(logging) {
console.log(logging); // parameter
console.log(this.logging); // property
console.log(getLogging()); // local variable
}
}
myObj = new MyClass();
myObj.myFunction(false);
Upvotes: 1
Reputation: 1380
Try to define logging as a Property of MyClass. This should work:
var MyClass = function() {
this.logging = true;
}
MyClass.prototype.myFunction = function(logging) {
/*References the logging-Property of the MyClass-Object:*/
var log1 = this.logging;
/*References the parameter:*/
var log2 = logging;
}
myObj = new MyClass();
myObj.myFunction(false);
Upvotes: 0
Reputation: 413712
In your code, the formal parameter of that anonymous function you create has the same name as the local variable ("logging" in both cases). Inside that anonymous function (the one that ends up as the "myFunction" property), the symbol "logging" will refer to the parameter. There is no way to access the local variable that's also called "logging".
The solution to this is to give the parameter a different name.
Note that this.logging
would refer to the property named "logging", if there were one. In the code you've posted, there isn't any such property.
Upvotes: 0