Forum Moderators: open

Message Too Old, No Replies

Creating "dot" functions

         

csdude55

8:10 pm on Nov 2, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Let's say that I have a script like:

function foo(bar) {
return bar + 1;
}

var lorem = foo(1);


How can I modify the function so that I could use 1.foo() (or, I guess, in this case it'd have to be '1'.foo() ) instead of foo(1)?


Note: the actual issue here is that I'm dealing with a third party script error:

foo.bar.getURL is not a function
foo.bar.isDefined is not a function

The only solution I can think of is to use typeof on my end to see if the functions exist, and if not then recreate them and simply return false. This sorta-kinda works:

if (typeof foo === 'undefined')
var foo = {};

if (typeof foo.bar === 'undefined')
foo.bar = [];

Object.prototype.isDefined = () => { return false; }

but it assumes that "foo.bar" will always be the variable name.

My theory is that if foo.bar.isDefined can be made equivalent to isDefined(foo) then I can avoid trying to recreate foo.bar.

webcat

1:00 am on Jun 23, 2024 (gmt 0)

Top Contributors Of The Month



Is the function name the same as one in the third-party script or something? It sounds like a roundabout way to fix the problem, but this would do what you want on its own. Can't say for sure if it would play nice with the third-party script:

Number.prototype.foo = function() {
return this + 1;
}

console.log((1).foo()); // 2

csdude55

5:06 am on Jun 23, 2024 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Shoot, that was 7 months ago! LOL I have no idea what I was trying to do now, there's been too much time and too much whisky between then and now ;-P

Thanks for the reply, though! I'll see if I can figure out what I was doing, and I'll report back if I still need help.

webcat

4:32 pm on Jun 23, 2024 (gmt 0)

Top Contributors Of The Month



Haha - I didn't notice the date. Ah well :)