JavaScript Object Methods
- Previous Page JS Object Properties
- Next Page JS Object Display
Example
var person = { firstName: "Bill", lastName : "Gates", id : 648, fullName : function() { return this.firstName + " " + this.lastName;
JavaScript methods
JavaScript methods are actions that can be performed on objects.
JavaScript MethodisFunction definitionproperties.
Property | value |
---|---|
firstName | Bill |
lastName | Gates |
age | 62 |
eyeColor | blue |
fullName | function() {return this.firstName + " " + this.lastName;} |
Methods are functions stored as object properties.
this keyword
in JavaScript, is called this
things, refers to the object that owns the JavaScript code.
this
value, when used in a function, is the object that "owns" the function.
Please note this
is not a variable. It is a keyword. You cannot change this
value.
Access object methods
Please use the following syntax to create object methods:
methodName : function() { Code line
Please use the following syntax to access object methods:
objectName.methodName()
You usually describe fullName() as a method of the person object, and fullName as a property.
The fullName property is executed as a function when called with ()
This example accesses person object's fullName() Method:
Example
name = person.fullName();
If you access fullName PropertyIf () is not used when defining a function, it will returnFunction definition:
Example
name = person.fullName;
Use built-in methods
This example uses the String object's toUpperCase()
Method, convert text to uppercase:
var message = "Hello world!"; var x = message.toUpperCase();
The value of x will be after the above code is executed:
HELLO WORLD!
Add New Method
Adding methods to objects is done within the constructor function:
Example
function person(firstName, lastName, age, eyeColor) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.eyeColor = eyeColor; this.changeName = function (name) { this.lastName = name;
The value of the name parameter of the changeName() function is assigned to the lastName property of the person.
Now you can try:
myMother.changeName("Jobs");
By using 'myMother' instead of 'this', JavaScript makes it clear which person you are referring to.
- Previous Page JS Object Properties
- Next Page JS Object Display