JavaScript is a flexible language where functions and objects work closely together.
- Functions as objects
- Function constructor
-
thiskeyword
1. Functions as Objects
In JavaScript, functions are special types of objects.
This means:
- Functions can be stored inside objects
- Functions can have properties
Example: Function inside Object
const user = {
name: "Athithya",
greet: function() {
return "Hello " + this.name;
}
};
console.log(user.greet());
Output:
Hello Athithya
Explanation
-
user→ object -
greet→ function (method) -
this.name→ refers to object value
Functions Can Have Properties
function greet() {}
greet.msg = "Hello";
console.log(greet.msg);
Output:
Hello
So, functions behave like objects.
2. Function Constructor
What is it?
A constructor function is used to create multiple objects using new.
Example
function Student(name, age) {
this.name = name;
this.age = age;
this.display = function() {
return this.name + " " + this.age;
};
}
let s1 = new Student("Ram", 20);
console.log(s1.display());
Output:
Ram 20
Explanation
-
Student→ constructor function -
this.name→ assign value -
new Student()→ creates object
3. this Keyword
this refers to the current object.
Example
const user = {
name: "Athithya",
show: function() {
console.log(this.name);
}
};
user.show();
Output:
Athithya
Explanation
-
this.name→ refers to object'sname - Inside object →
this= that object
Top comments (0)