How to make a class in JavaScript?

前端 未结 4 1463
感情败类
感情败类 2020-12-12 01:38

There are lots of ways of doing the same thing in JavaScript. I have however picked up some ways, and some ways I frankly don\'t understand. Could anyone please help me clar

4条回答
  •  不知归路
    2020-12-12 02:21

    I think there are some concepts that seem to be missing but I'll try answering as much as I can.

    So a class can be made like this...Is this all correct so far?

    It's close but is not entirely correct. You don't need new to create a constructor function, you only need it when creating a new instance of the "class".

    function Klass() { ... } // capitalized name as convention for constructors
    var myKlass = new Klass(); //<-- Need "new" here
    

    Public methods can be attached to the instance or to the prototype. When you attach it to the prototype the method will be shared across all instances, saving some memory.

    Klass.prototype = {
      publicSharedMethod: function() {
        var self = this;
      }
    }
    

    Then someone likes the self-executing anonymous function... What is the point of that...

    The module pattern (or self-execution function) approach is a bit different because you're typically not dealing with the prototype although you can. It's just a function that returns a literal object with properties and methods but I mainly use it for singletons when you don't need instances of that object:

    var Singleton = (function() {
      var private = 'foo';
      var public = 'baz';
      var publicMethod = function() { ... }
      // Expose public methods and properties
      return {
        public: public
        publicMethod: publicMethod
      }
    }());
    

    And lastly you have the object literal notation that I don't understand.

    That's just a regular object in JavaScript, similar to what PHP calls "associative array". Literal objects syntax are the base for JSON, but JSON has more limitations in terms of formatting; JavaScript is more forgiving so you can have unquoted properties and methods for example.

    Why would you prototype instead of making the class correctly the first time?

    The point here is to understand that JavaScript is not a traditional object oriented language, so there are no classes, and you shouldn't be thinking about classes. But prototypes are very powerful, I'd say even more powerful than classes. There are many examples online on how to replicate classes with prototypes but not the other way around.

提交回复
热议问题