Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the same method when chaining over an object?

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?

like image 890
faiizow Avatar asked Apr 06 '26 06:04

faiizow


1 Answers

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.

like image 139
gustavotkg Avatar answered Apr 08 '26 19:04

gustavotkg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!