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
William Troup
13.2k24 gold badges76 silver badges100 bronze badges
1 Answer 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
cliffs of insanity
3,7041 gold badge18 silver badges18 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js