Constructors in JavaScript objects

后端 未结 19 1734
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

相关标签:
19条回答
  • Yes, you can define a constructor inside a class declaration like this:

    class Rectangle {
      constructor(height, width) {
        this.height = height;
        this.width = width;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 10:32

    Using Nick's sample above, you can create a constructor for objects without parameters using a return statement as the last statement in your object definition. Return your constructor function as below and it will run the code in __construct each time you create the object:

    function Box()
    {
       var __construct = function() {
           alert("Object Created.");
           this.color = 'green';
       }
    
      this.color = '';
    
       this.getColor = function() {
           return this.color;
       }
    
       __construct();
    }
    
    var b = new Box();
    
    0 讨论(0)
  • 2020-11-22 10:33

    Example here: http://jsfiddle.net/FZ5nC/

    Try this template:

    <script>
    //============================================================
    // Register Namespace
    //------------------------------------------------------------
    var Name = Name||{};
    Name.Space = Name.Space||{};
    
    //============================================================
    // Constructor - MUST BE AT TOP OF FILE
    //------------------------------------------------------------
    Name.Space.ClassName = function Name_Space_ClassName(){}
    
    //============================================================
    // Member Functions & Variables
    //------------------------------------------------------------
    Name.Space.ClassName.prototype = {
      v1: null
     ,v2: null
     ,f1: function Name_Space_ClassName_f1(){}
    }
    
    //============================================================
    // Static Variables
    //------------------------------------------------------------
    Name.Space.ClassName.staticVar = 0;
    
    //============================================================
    // Static Functions
    //------------------------------------------------------------
    Name.Space.ClassName.staticFunc = function Name_Space_ClassName_staticFunc(){
    }
    </script>
    

    You must adjust your namespace if you are defining a static class:

    <script>
    //============================================================
    // Register Namespace
    //------------------------------------------------------------
    var Shape = Shape||{};
    Shape.Rectangle = Shape.Rectangle||{};
    // In previous example, Rectangle was defined in the constructor.
    </script>
    

    Example class:

    <script>
    //============================================================
    // Register Namespace
    //------------------------------------------------------------
    var Shape = Shape||{};
    
    //============================================================
    // Constructor - MUST BE AT TOP OF FILE
    //------------------------------------------------------------
    Shape.Rectangle = function Shape_Rectangle(width, height, color){
        this.Width = width;
        this.Height = height;
        this.Color = color;
    }
    
    //============================================================
    // Member Functions & Variables
    //------------------------------------------------------------
    Shape.Rectangle.prototype = {
      Width: null
     ,Height: null
     ,Color: null
     ,Draw: function Shape_Rectangle_Draw(canvasId, x, y){
        var canvas = document.getElementById(canvasId);
        var context = canvas.getContext("2d");
        context.fillStyle = this.Color;
        context.fillRect(x, y, this.Width, this.Height);
     }
    }
    
    //============================================================
    // Static Variables
    //------------------------------------------------------------
    Shape.Rectangle.Sides = 4;
    
    //============================================================
    // Static Functions
    //------------------------------------------------------------
    Shape.Rectangle.CreateSmallBlue = function Shape_Rectangle_CreateSmallBlue(){
        return new Shape.Rectangle(5,8,'#0000ff');
    }
    Shape.Rectangle.CreateBigRed = function Shape_Rectangle_CreateBigRed(){
        return new Shape.Rectangle(50,25,'#ff0000');
    }
    </script>
    

    Example instantiation:

    <canvas id="painting" width="500" height="500"></canvas>
    <script>
    alert("A rectangle has "+Shape.Rectangle.Sides+" sides.");
    
    var r1 = new Shape.Rectangle(16, 12, "#aa22cc");
    r1.Draw("painting",0, 20);
    
    var r2 = Shape.Rectangle.CreateSmallBlue();
    r2.Draw("painting", 0, 0);
    
    Shape.Rectangle.CreateBigRed().Draw("painting", 10, 0);
    </script>
    

    Notice functions are defined as A.B = function A_B(). This is to make your script easier to debug. Open Chrome's Inspect Element panel, run this script, and expand the debug backtrace:

    <script>
    //============================================================
    // Register Namespace
    //------------------------------------------------------------
    var Fail = Fail||{};
    
    //============================================================
    // Static Functions
    //------------------------------------------------------------
    Fail.Test = function Fail_Test(){
        A.Func.That.Does.Not.Exist();
    }
    
    Fail.Test();
    </script>
    
    0 讨论(0)
  • 2020-11-22 10:34

    This is a constructor:

    function MyClass() {}
    

    When you do

    var myObj = new MyClass();
    

    MyClass is executed, and a new object is returned of that class.

    0 讨论(0)
  • 2020-11-22 10:34

    I guess I'll post what I do with javascript closure since no one is using closure yet.

    var user = function(id) {
      // private properties & methods goes here.
      var someValue;
      function doSomething(data) {
        someValue = data;
      };
    
      // constructor goes here.
      if (!id) return null;
    
      // public properties & methods goes here.
      return {
        id: id,
        method: function(params) {
          doSomething(params);
        }
      };
    };
    

    Comments and suggestions to this solution are welcome. :)

    0 讨论(0)
  • 2020-11-22 10:35

    In JavaScript the invocation type defines the behaviour of the function:

    • Direct invocation func()
    • Method invocation on an object obj.func()
    • Constructor invocation new func()
    • Indirect invocation func.call() or func.apply()

    The function is invoked as a constructor when calling using new operator:

    function Cat(name) {
       this.name = name;
    }
    Cat.prototype.getName = function() {
       return this.name;
    }
    
    var myCat = new Cat('Sweet'); // Cat function invoked as a constructor
    

    Any instance or prototype object in JavaScript have a property constructor, which refers to the constructor function.

    Cat.prototype.constructor === Cat // => true
    myCat.constructor         === Cat // => true
    

    Check this post about constructor property.

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