var string = function (base) {
return {
add: function (added) {
return base + added;
}
}
}
text = string("robots").add(" are awesome");
console.log(text);
// robots are awesome
text2 = string("robots").add(" are awesome").add(" everytime!");
console.log(text2);
// TypeError: Object robots are awesome has no method 'add'
How do I make this work? What can you do to share the method 'add' across certain objects within the scope of the function?
If you only return string(base + added). It won't work properly. It'll return an Object when you console.log.
var string = function (base) {
return {
add: function (added) {
return string(base + added);
}
}
}
console.log(string("test ").add("this ").add("thing"));
// outputs [object Object]
Above example fails for what you want. You may try this:
var string = function (base) {
return {
add: function (added) {
base += added;
return string(this.toString());
},
toString: function() {
return base;
}
}
}
console.log(string("test ").add("this ").add("thing").toString());
// outputs "test this thing"
This will output correctly.
You also could extend String.prototype and add the add method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With