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);