What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1455
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

相关标签:
19条回答
  • 2020-11-22 07:54

    Based on the example of Triptych, this might even be simpler:

        // Define a class and instantiate it
        var ThePerson = new function Person(name, gender) {
            // Add class data members
            this.name = name;
            this.gender = gender;
            // Add class methods
            this.hello = function () { alert('Hello, this is ' + this.name); }
        }("Bob", "M"); // this instantiates the 'new' object
    
        // Use the object
        ThePerson.hello(); // alerts "Hello, this is Bob"
    

    This only creates a single object instance, but is still useful if you want to encapsulate a bunch of names for variable and methods in a class. Normally there would not be the "Bob, M" arguments to the constructor, for example if the methods would be calls to a system with its own data, such as a database or network.

    I am still too new with JS to see why this does not use the prototype thing.

    0 讨论(0)
  • 2020-11-22 07:54

    //new way using this and new
    function Persons(name) {
      this.name = name;
      this.greeting = function() {
        alert('Hi! I\'m ' + this.name + '.');
      };
    }
    
    var gee=new Persons("gee");
    gee.greeting();
    
    var gray=new Persons("gray");
    gray.greeting();
    
    //old way
    function createPerson(name){
     var obj={};
     obj.name=name;
     obj.greeting = function(){
     console.log("hello I am"+obj.name);
     }; 
      return obj;
    }
    
    var gita=createPerson('Gita');
    gita.greeting();

    0 讨论(0)
  • 2020-11-22 07:57

    The best way to define a class in JavaScript is to not define a class.

    Seriously.

    There are several different flavors of object-orientation, some of them are:

    • class-based OO (first introduced by Smalltalk)
    • prototype-based OO (first introduced by Self)
    • multimethod-based OO (first introduced by CommonLoops, I think)
    • predicate-based OO (no idea)

    And probably others I don't know about.

    JavaScript implements prototype-based OO. In prototype-based OO, new objects are created by copying other objects (instead of being instantiated from a class template) and methods live directly in objects instead of in classes. Inheritance is done via delegation: if an object doesn't have a method or property, it is looked up on its prototype(s) (i.e. the object it was cloned from), then the prototype's prototypes and so on.

    In other words: there are no classes.

    JavaScript actually has a nice tweak of that model: constructors. Not only can you create objects by copying existing ones, you can also construct them "out of thin air", so to speak. If you call a function with the new keyword, that function becomes a constructor and the this keyword will not point to the current object but instead to a newly created "empty" one. So, you can configure an object any way you like. In that way, JavaScript constructors can take on one of the roles of classes in traditional class-based OO: serving as a template or blueprint for new objects.

    Now, JavaScript is a very powerful language, so it is quite easy to implement a class-based OO system within JavaScript if you want to. However, you should only do this if you really have a need for it and not just because that's the way Java does it.

    0 讨论(0)
  • 2020-11-22 07:58

    A base

    function Base(kind) {
        this.kind = kind;
    }
    

    A class

    // Shared var
    var _greeting;
    
    (function _init() {
        Class.prototype = new Base();
        Class.prototype.constructor = Class;
        Class.prototype.log = function() { _log.apply(this, arguments); }
        _greeting = "Good afternoon!";
    })();
    
    function Class(name, kind) {
        Base.call(this, kind);
        this.name = name;
    }
    
    // Shared function
    function _log() {
        console.log(_greeting + " Me name is " + this.name + " and I'm a " + this.kind);
    }
    

    Action

    var c = new Class("Joe", "Object");
    c.log(); // "Good afternoon! Me name is Joe and I'm a Object"
    
    0 讨论(0)
  • 2020-11-22 08:00

    The simple way is:

    function Foo(a) {
      var that=this;
    
      function privateMethod() { .. }
    
      // public methods
      that.add = function(b) {
        return a + b;
      };
      that.avg = function(b) {
        return that.add(b) / 2; // calling another public method
      };
    }
    
    var x = new Foo(10);
    alert(x.add(2)); // 12
    alert(x.avg(20)); // 15
    

    The reason for that is that this can be bound to something else if you give a method as an event handler, so you save the value during instantiation and use it later.

    Edit: it's definitely not the best way, just a simple way. I'm waiting for good answers too!

    0 讨论(0)
  • 2020-11-22 08:02

    Object Based Classes with Inheritence

    var baseObject = 
    {
         // Replication / Constructor function
         new : function(){
             return Object.create(this);   
         },
    
        aProperty : null,
        aMethod : function(param){
          alert("Heres your " + param + "!");
        },
    }
    
    
    newObject = baseObject.new();
    newObject.aProperty = "Hello";
    
    anotherObject = Object.create(baseObject); 
    anotherObject.aProperty = "There";
    
    console.log(newObject.aProperty) // "Hello"
    console.log(anotherObject.aProperty) // "There"
    console.log(baseObject.aProperty) // null
    

    Simple, sweet, and gets 'er done.

    0 讨论(0)
提交回复
热议问题