Pseudo-classical vs. “The JavaScript way”

后端 未结 4 710
野趣味
野趣味 2021-01-30 03:22

Just finished reading Crockford\'s \"JavaScript: The Good Parts\" and I have a question concerning his stance on the psuedo-classical vs. prototypal approaches.

4条回答
  •  [愿得一人]
    2021-01-30 03:57

    Javascript isn't a person so she can't really suggest what you do.

    None of the answers above have mentioned the plain-old functional style of inheritance, which I tend to find is the simplest.

    function myModuleMaker(someProperty){
      var module = {}; //define your new instance manually
    
      module.property = someProperty; //set your properties
    
      module.methodOne = function(someExternalArgument){
        //do stuff to module.property, which you can, since you have closure scope access
      return module;
      }
    }
    

    Now to make a new instance:

    var newModule = myModuleMaker(someProperty);
    

    You still get all the benefits of pseudoclassical this way, but you suffer the one drawback that you're making a new copy of all your instance's methods every time you instantiate. This is probably only going to matter when you start having many hundreds (or indeed, thousands) of instances, which is a problem most people seldom run into. You're better off with pseudoclassical if you're creating truly enormous data structures or doing hard-core animations with many, many instances of something.

    I think it's hard to argue that either method is "bad practice" per se.

提交回复
热议问题