The fundamental point here is that this line is wrong for either given implementation of Text
:
var text = Text('hello').trim().bold();
...because within Text
you're storing properties on this
, but when you call Text
the way you have above, this
is either the global object (in loose mode) or undefined
(in strict mode). In loose mode, you're creating/overwriting globals called value
, trim
, and bold
(because you're writing properties to the global object, and all properties of the global object are globals); in strict mode, you'd get an exception because you can't assign properties to undefined
.
Instead, you'd have to call it like this:
var text = new Text('hello').trim().bold();
// Note ---^^^
And that should answer your question about trim
and bold
(e.g., you need the second version, the version that uses new
). Separately, the return this;
at the end is unnecessary if the function is called with new
.
If you want to call Text
without using new
, you can, but the implementation has to be different — it has to create the object it returns, since new
isn't doing that for it:
function makeText(text) {
var obj = {};
obj.value = text;
obj.trim = function() { /* trim code */ return makeText(this.value); };
obj.bold = function() { /* bold code */ return makeText(this.value); };
return obj;
}
or more concisely:
function makeText(text) {
return {
value: text,
trim: function() { /* trim code */ return makeText(this.value); },
bold: function() { /* bold code */ return makeText(this.value); }
};
}
Note I changed the name so it no longer started with a capital letter; in JavaScript, the overwhelming convention is that functions starting with capital letters are constructor functions (functions you call via new
in the normal case).