Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a "dot function" in javascript

Tags:

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?

like image 911
Oliver Ni Avatar asked Nov 09 '13 05:11

Oliver Ni


People also ask

How do you make a dot in JavaScript?

To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console. log(cat.name);

What is Dot function in JS?

The JavaScript dot (.) operator is simply an operator that sits between its operands, just like + and -. The variables stored in an object that we access via the dot operator are generically called properties. object.property.

What are the double dots in JavaScript?

It does the same thing as the single dot operator, which selects children, but it selects all descendants. (It's by analogy with XPath's / operator selecting children of an element that match the selector and // selecting all descendants that match the selector.)


2 Answers

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());  
like image 141
Paul Draper Avatar answered Sep 18 '22 21:09

Paul Draper


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

  • Inheritance and the prototype chain
like image 29
p.s.w.g Avatar answered Sep 20 '22 21:09

p.s.w.g