William Troup
William Troup

Reputation: 13131

Class Function Call

I have a class setup as follows:

var oTest = new TEST();

function TEST() {

  this.String = function(sString) {

    this.Trim = function() {
    }
  }
}

I want to be able to call the Trim function as follows:

var sTrimmed = oTest.String("  something").Trim();

Is this the correct approach? Any help would be greatly appreciated as i have never done functions inside class functions before.

Upvotes: 0

Views: 116

Answers (1)

cliffs of insanity
cliffs of insanity

Reputation: 3694

Add your methods to the prototype of the constructor function, and do return this; in String, to return the same object, which makes it chainable.

var oTest = new TEST();

function TEST() {}

TEST.prototype.String = function(aString) {
    this.the_string = aString;
    return this;
};
TEST.prototype.Trim = function() {
    this.the_string = this.the_string.trim();
    return this;
};
TEST.prototype.getString = function() {
    return this.the_string;
};

var sTrimmed = oTest.String("  something")
                    .Trim()
                    .getString();

live demo: http://jsfiddle.net/BcwgC/

Upvotes: 1

Related Questions