How to create OOP Class in Javascript

后端 未结 3 1720
闹比i
闹比i 2021-01-16 05:59

I\'m hesitant to use just any tutorial because I know how those tutorials can end up being, teaching you bad ways to do things. I want to setup a class in Javascript, so th

相关标签:
3条回答
  • 2021-01-16 06:16

    Although there are no classes in JavaScript, you can create constructor functions. A constructor function works by binding methods to an objects prototype. There are several ways to do this, each with advantages and disadvantages. I personally prefer the most straigthforward way, which works by appending methods to "this":

    var Constructor = function() {
    
      //object properties can be declared directly
      this.property = "value";
    
      //to add a method simply use dot notation to assign an anonymous function to an object
      //property
      this.method = function () {
        //some code
      }
    
      //you can even add private functions here. This function will only be visible to this object methods
      function private() {
        //some code
      }
      //use return this at the end to allow chaining like in var object = new Constructor().method();
      return this; 
    
    }
    
    0 讨论(0)
  • 2021-01-16 06:43

    There is no such thing as a class in JavaScript, instead everything in JavaScript is an object.

    To create a new object you define a function that uses the this keyword in it (a “constructor function”), and then call it with the new operator:

    function Foo (id) { // By convention, constructor functions start with a capital letter
        this.id = id;
    }
    
    var foo1 = new Foo(1);
    var foo2 = new Foo(2);
    

    However, these objects have no methods. To add methods, you need to define a prototype object on their constructor function:

    Foo.prototype = {
        getId: function () {
            return this.id;
        }
    }
    

    This new getId function will be usable by all Foo objects. However, as was stated, there are no classes in JavaScript and as such there are other constructs you will use in order to produce different results.

    I highly recommend the videos by Douglas Crockford in which he explains much of the javascript OO nature. The talks can be found here:

    http://developer.yahoo.com/yui/theater/

    Douglas Crockford — The JavaScript Programming Language

    Douglas Crockford — Advanced JavaScript

    Those will give you a basic understanding of the structure of javascript and should help the transition from classical to functional programming.

    0 讨论(0)
  • 2021-01-16 06:43

    There is nothing like classes in JavaScript. JavaScripts inheritance works with prototypes. You can take a look at base2, which mimics class-like behaviour in JavaScript.

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