JasperTack
JasperTack

Reputation: 4447

the proper way to write an initialize function

I want to use an initialization function that will be called after a user visits a part of the application, but after that first visit I don't want to initialize anymore. A simple way to do this is using a flag and an if-statement, but there is a nicer solution to this problem: in other languages I changed the body of the init function so that after the call of this method.

Can this be done in Javascript too? I wrote something like this, but eclipse says that it is an illegal assignment:

function initEdit(){
...

this = function() {};
}

Upvotes: 0

Views: 169

Answers (1)

Guffa
Guffa

Reputation: 700182

Yes, you can, but this doesn't refer to the function, so you have to specify it by name:

function initEdit(){
  ...

  initEdit = function() {};
}

Another alternative, that might be easier to follow, is to just use a variable:

var initialised = false;

function initEdit(){
  if (!initialised) {
    initialised = true;
    ...
  }
}

Upvotes: 2

Related Questions