The this Keyword
In a function definition, this
refers to the "owner" of the function.
this
is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
JavaScript Methods
JavaScript methods are actions that can be performed on objects.
A JavaScript method is a property containing a function definition.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() {return this.firstName + " " + this.lastName;} |
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
Example(1)
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:
Example(2)
name = person.fullName;
Using Built-In Methods
This example uses the toUpperCase()
method of the String object, to convert a text to uppercase:
example(4)
var message = "Hello world!"; var x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
Adding a Method to an Object
Adding a new method to an object is easy:
Example(5)
person.name = function() { return this.firstName + " " + this.lastName; };
Complete Code For Object Functions Used In Java Script.
<!DOCTYPE html> <html> <head> <title>Which Are The Object Functions Used In Java Script</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <style> body{ background: black; } </style> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: White">Which Are The Object Functions Used In Java Script</h1> </div> <div class="well"> <h2 id="demo1"></h2> <script> var person = { firstName: "John", lastName : "Doe", id : 5566, }; person.name = function() { return this.firstName + " " + this.lastName; }; document.getElementById("demo1").innerHTML = "My father is " + person.name(); </script> </div> </div> </body> </html>