How can I set state https://jsfiddle.net/7q1530sp/10/ doesn't work
function o(){
this.state = true;
}
o.f = function() {
alert(this.state);
}
o.state = false;
o();
o.f();
instead of refering to o explicitely within its function https://jsfiddle.net/7q1530sp/9/
function o(){
o.state = true;
}
o.f = function() {
alert(this.state);
}
o.state = false;
o();
o.f();
Is there a way to refer to o without using its name ?
CodePudding user response:
Usually, to initialize a function you should use NEW before executing it, example:
var my = new fn()
However, I would advise you to opt for prototypes:
In addition to being comfortable to use, in case of complex projects, they will also allow you to divide your project into multiple files while keeping the code clean and tidy!
I leave you a small example on how prototypes are used:
var my = function(){}
my.prototype.test = true;
my.prototype.run = function(){
console.log(this.test)
}
var w = new my();
w.run();
w.test = false;
w.run();
Update: Of course, you could also globally change the value of the variable like so:
var my = function(){}
my.prototype.test = true;
my.prototype.run = function(){
console.log(this.test)
}
new my().run();
my.prototype.test = false;
new my().run();
Output:
true
false