What is a JavaScript method?
Javascript contains objects, which are things like a document, a window or a frame.
Objects can also be something that you define yourself. This is an object:
var cricketer = {firstName:"Ricky", lastName:"Ponting", age:41, batAvg: 51.85};
A method is a function that is performed on an object. Methods belong to objects.
Here’s the object from earlier, this time with a method called getSummary
attached:
var cricketer = {firstName:"Ricky", lastName:"Ponting", age:41, batAvg: 51.85,
getSummary: function() {
return "Name: " + this.firstName + " " + this.lastName + " Average: " + this.batAvg
}};
Lots of things have methods attached to them. Strings have methods:
"HELLO".toLowerCase() // "hello"
Numbers have methods through the Math object. The Math object has a set of methods that can be applied to numbers.
Math.floor(40.1) // 40
Arrays have methods too
var firstArray = ["Hello"]
var secondArray = ["my","friend"]
firstArray.concat(secondArray) // ["Hello", "my", "friend"]
as do functions
var add = function(x){
sum = 0
for(var i = 0; i < arguments.length; i++){
sum = sum + arguments[i];
}
return sum;
}
array = [1,2,6,1,2,6]
add.apply(null,array) //18
and so does the RegExp type
var a = /greet/
testString = "greetings"
a.test(testString) //true
Useful things, methods.