How to make a "dot function" in javascript
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
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());