25

I'm trying to define a "dot function" where there are no parameters but has a . and a string or number before it like these:

.toUpperCase()
.toLowerCase()
.indexOf()
.charAt()
.substring()

You do 2..toString, not toString(2).

How do you define one of them?

Oliver Ni
  • 2,606
  • 7
  • 29
  • 44

3 Answers3

30

Defining a "dot function" is easy. Here's how you can define it on a single object.

var a = {}, or a = function() {}, or a = [], etc.

a.dotFunction = function() { return 'hi'; }

console.log(a.dotFunction());

If you want to define it on all instances of a "class", use prototype.

function someClass() {
}

someClass.prototype.dotFunction = function() { return 'hi'; };

console.log(new someClass().dotFunction());

You can even do this on built-in types (some, like Prototype.js, do this, though most recommended against it).

Number.prototype.dotFunction = function() { return 'hi'; };

console.log((0).dotFunction()); 
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
19

I'd strongly recommend not trying to replace any built-in methods, however, you're free to define your own methods however you like.

You can do this by attaching the method to the Number or String type's prototype:

Number.prototype.foo = function(n) { return this * n; };
String.prototype.bar = function(n) { return this.length * n; };

alert(4..foo(2));  // 8
alert("4".bar(2)); // 2

Further Reading

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • And you're not going to include any of the reasons why it's often bad to add methods to the built-in types? Also, why two periods in your first `alert()`? – jfriend00 Nov 09 '13 at 06:37
  • @jfriend00 I think JS parser needs 2 dots otherwise with only one lookahead it can't decide if its a fractional number or a dot for method access with only a single dot. – alex Apr 05 '16 at 11:19
-1

I'll give it a shot because nobody mentioned that you can already do this without having to define anything yourself.

A thing to take care of is if you have a number you have to place 2 dots after it where as if you have a function that returns a number or a variable that holds one you don't:

1..toString()
 .indexOf("1")//<=returns number 0
 //even though a number is returned we only need one dot here
 .toString();//<="0"

var num = 1234;
num.toString()//<=one dot
  .indexOf("23");//<=1

Your example would already work but since indexOf would return a number if you give it an argument that makes sense and a number doesn't have a charAt method.

"hello".toUpperCase()
  .toLowerCase()
  .indexOf("h")//<=returns a number 
               //number has no charAt method
  .toString()
  .charAt(0)
  .substring(0);//<="0"
HMR
  • 37,593
  • 24
  • 91
  • 160