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?
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);
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.
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.)
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());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With