简体   繁体   中英

Best way to define obj constructor in namespace javascript

I want to keep obj consructors in some namespace with having no problems on debug.

Right now I have code like this:

var namespace = {};
namespace.myConstructor = function(){};
// ----------- debug in console
(new namespace.myConstructor()); // -> namespace.myConstructor {}
(new namespace.myConstructor()).constructor; // -> function (){}

I dont like that constructor is anonymous. So I could do it in other ways:

(better, but ugly)

var namespace = {};
namespace.myConstructor = (function(){
  function myConstructor(){};
  return myConstructor;
})();
// ----------- debug in console
(new namespace.myConstructor()); // -> myConstructor {}
(new namespace.myConstructor()).constructor; // -> function myConstructor(){}

or (the most beautful and shortest way)

namespace.myConstructor = function myConstructor(){};
// ----------- debug in console
(new namespace.myConstructor()); // -> myConstructor {}
(new namespace.myConstructor()).constructor; // -> function myConstructor(){}

But I read here , that there are some problems with NFE (Named Function Expression).

Which way is better? Which way is good practice?

The IE8 problems are exaggerated and don't really matter at all in practice because the functions will be declared in short-lived IIFEs that cannot reference the function by name anyway because then your code will not work in a real browser.

Remember to capitalize constructor names.

(function(){
    var namespace = {
        MyConstructor: function MyConstructor() {

        },

        ...
    }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM