开发者

JavaScript: Closures help

开发者 https://www.devze.com 2022-12-19 09:21 出处:网络
I have an empty .js file with this code in it: Cart.CheckoutNow = { ... } // Alias if (typeof(CheckoutNow) === \'undefined\') {

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 alread开发者_StackOverflowy a variable in window.');
 }
};

Cart.CheckoutNow = {
 ...
};

alias();


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


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 = {
  ...
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消