I am studying JavaScript and being confused with its Object concept. I used to be a Java programmer and it is terrifying me that JavaScript does not have class.
From what I've learnt so far, function can replace class in JavaScript. and you can instantiate the function by using the 'new
' keyword like below.
function person() {
var name;
this.tellYourName = function() {
return 'My name is ' + name;
}
this.setName = function(newName) {
name = newName;
}
}
var person1 = new person();
person1.setName('Chris');
alert(person1.tellYourName());
in the code above, I created an object 'person1' inheriting the properties from person function.
So here's my question.
is person() an object? what I meant by object is whether the person()
is a class or an instantiated object.
I was confused with this concept when I was studying closure. Here's the sample code
function closureTest(a) {
return function(b) {
return a + b;
}
}
var test = closureTest(1);
alert(test(2));
Here I guess the closureTest function works as a method not a class. and var test = closureTest(1);
line did not use the 'new
' keyword. That means test variable will store the return value from the closureTest(1);
But as you see the test variable is used as a an object of closureTest
. How is this possible? because when I tried it with the test code below
function test(a) {
return a;
}
var t = test(2);
alert(t);
prints out the return value of the test function as I expected.
I hope my question is not too confusing. I currently moved from Java to JavaScript and my thought that they will be almost same is all wrong. I read several lectures about Object concept in JavaScript but it get even more confusing. Thanks for your time reading this and hope I can get something from you :)