javascript - Create a prototype method that works alone but can also have sub-methods -
i don't know how else name title, sorry.
here example, want able this:
var str = 'bla bla bla'; str.do(a).thendo(b) //but want able this: str.do(a) // different // have tried doesn't work: string.prototype.do = function(a) { //here code 'str' variable, then: var self = {}; self.thendo = function(b) { var somecalculations; return somecalculations + + b; } self = function() { //this supposed do(a) function var morecalculations; return morecalculations + a; } return self; }
note: thendo() needs use 'a' parameter do() not in i'm trying achieve:
string.prototype.do = function(a) { var morecalculations; return morecalculations + a; } string.prototype.do.thendo = function(b) { var somecalculations; return somecalculations + + b; } //it doesnt work, thendo() cant 'a' parameter
furthermore need library i'm developing jquery answers not help.
thanks
you've said:
str.do(a).thendo(b) //but want able this: str.do(a) // different
it's impossible do(a)
part of different depending on whether return value used. e.g., do(a)
part of str.do(a)
, str.do(a).thendo(b)
cannot know it's meant different in 2 cases. doesn't have information (which thing™).
you make work:
str.do(a)(); // 1 thing str.do(a).thendo(b); // else
note ()
@ end of first one. that's trigger lets differentiate 2 cases:
(function() { function string$do(v1) { // function called if caller uses () on result function immediate() { console.log("something: ", v1); } // called if use .thendo() instead immediate.thendo = function(v2) { console.log("something else: ", 1, v2); }; return immediate; } object.defineproperty(string.prototype, "do", { value: string$do }); })(); var str = "testing 1 2 3"; str.do(42)(); str.do(42).thendo(67);
side note: when extending built-in prototypes (which many advocate against), always sure use object.defineproperty
or object.defineproperties
, use default enumerable
flag (or explicitly set false
) don't create enumerable property. won't naming conflicts, may code naively assuming default set of built-in prototype properties in for-in
loops, in
checks, etc.
Comments
Post a Comment