0

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.

Piotr
5,5631 gold badge35 silver badges37 bronze badges
asked May 8, 2012 at 12:40
0

1 Answer 1

1

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/

answered May 8, 2012 at 12:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.