views:

83

answers:

3

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();
A: 

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

Ravia
+1  A: 

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 = {
  ...
}
jvenema
+1  A: 

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();
}
Jimmy Cuadra