0

I have an empty .js file with this code in it:

Cart.CheckoutNow = {
 ...
}

// Alias

if (typeof(CheckoutNow) === 'undefined') {
    CheckoutNow = Cart.CheckoutNow;
}
else {
    alert('CheckoutNow is already a variable in window.');
}

How can I have the // Alias code appear at the top of the page, but have it execute after Cart.CheckoutNow is declared?

This would work, but I don't like that you have to call alert() at the bottom:

alias = function() {
 if (typeof(CheckoutNow) === 'undefined') {
  CheckoutNow = Cart.CheckoutNow;
 }
 else {
  alert('CheckoutNow is already a variable in window.');
 }
};

Cart.CheckoutNow = {
 ...
};

alias();
3
  • Btw, you want if( typeof CheckoutNow === 'undefined' ) without the braces around CheckoutNow. Commented Feb 2, 2010 at 6:09
  • btw, no need for strict comparaison, typeof always returns a String Commented Feb 3, 2010 at 14:34
  • The question doesn't seem to have anything to do with javascript closures, actually. Commented Feb 3, 2010 at 14:36

3 Answers 3

1

Without an explanation of why you're trying to do this, I'm going to guess that it's for better code organization. If that's the case, I would split your JavaScript up into multiple files something along the lines of this, and to be included on your page in this order:

// namespace.js
if (typeof Cart === 'undefined') {
    Cart = {};
}

// checkoutnow.js
Cart.CheckoutNow = {
    // module code here
}

// alias.js
alias = function() {
    // alias code here
}

// domready.js
onDocumentReadyFunction() {
    alias();
}
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure this is really what you want to be doing, but if you're sure, then what you want is:

window.setTimeout(function(){

  // Alias
  if (typeof CheckoutNow === 'undefined') {
    CheckoutNow = Cart.CheckoutNow;
  }
  else {
    alert('CheckoutNow is already a variable in window.');
  }

},0);

Cart.CheckoutNow = {
  ...
}

Comments

0

You would have to define Alias in a function and call it onload event of body.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.