How do you define JavaScript functions?
For example:
string.doSomething(); // OR
element.getSomeInfo();
I couldn't find anything on this, but maybe that's because it has a name I don't know.
EDIT
About four years later, let me rephrase this question to explain what I meant. I didn't know about objects, but essentially my question was "How do I define a function as a property of an object?". I wasn't necessarily differentiating between extending native Javascript classes (which is a bad idea) and just defining my own object with functions as properties.
So, to answer my own question, these are some different ways to do that:
const foo = {
bar: x => 1 / x;
}
so that, for example, foo.bar(4)
returns .25
. Another one:
function Rocket(speed){
this.speed = speed;
this.launch = () => {
this.speed = 'super fast and upwards';
}
}
So now one could define const Apollo = new Rocket('standing still');
and call Apollo.launch();
We can additionally extend such classes (including native ones) by
Rocket.prototype.stop = function(){
this.speed = 'Standing still';
}
and then call it using Apollo.stop();
.