Oliver Ni
Oliver Ni

Reputation: 2664

How to make a "dot function" in javascript

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?

Upvotes: 26

Views: 30529

Answers (3)

HMR
HMR

Reputation: 39270

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"

Upvotes: -1

p.s.w.g
p.s.w.g

Reputation: 149020

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

Upvotes: 19

Paul Draper
Paul Draper

Reputation: 83235

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()); 

Upvotes: 31

Related Questions