Lion King
Lion King

Reputation: 33813

Create a method which simulates a class constructor

I want to create a method which automatically implemented when create an instance of an object, exactly like concept of class constructor.

function myString(string) {
  // Storing the length of the string.
  this.length = 0;
  // A private constructor which automatically implemented
  var __construct = function() {
    this.getLength();
  }();
  // Calculates the length of a string
  this.getLength = function() {
    for (var count in string) {
      this.length++;
    }
  };
}

// Implementation
var newStr = new myString("Hello");
document.write(newStr.length);

I have the following error message when implement the previous code:
TypeError: this.getLength is not a function.


UPDATE:
The problem was in this scope. The following is constructor method after updade:

var __construct = function(that) {
  that.getLength();
}(this);

Upvotes: 1

Views: 83

Answers (1)

li x
li x

Reputation: 4061

Bergi's answer in this thread is far more relevant: How to define private constructors in javascript?

Though a bit crude you can create a method called init and then call that method at the bottom of your function so when you instantiate a new object that code shall be run.

  function myString(string) {

  //Initalization function
  this.init = function() {
    this.calcLength();
  }

  // Storing the length of the string.
  this.length = 0;

  this.getLength = function() {
    return this.length;
  }

  // Calculates the length of a string
  this.calcLength = function() {
    for (var count in string) {
      this.length++;
    }
  };

  this.init();
}

// Implementation
var newStr = new myString("Hello");
var element = document.getElementById('example');
element.innerText = newStr.getLength();

Edit: I'm aware there are better ways to achieve this, but this gets the job done.

Edit 2: Fiddle https://jsfiddle.net/ntygbfb6/3/

Upvotes: 1

Related Questions