Objects? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Objects?

what is objects? nd Constructors? in JavaScript.....

23rd Jul 2017, 5:34 AM
Vengatesharavinth P
Vengatesharavinth P - avatar
4 Answers
+ 4
if you have a constructor: function Animal(legs, sound) { this.legs = legs; this.sound = sound; // this is a method this.makeSound = function() { alert(this.sound); } } or in an object: var cat = {legs: 4, sound:"meow", makeSound: function() {alert(this.sound)}}; I'm not sure about the last one but I think if cat.makeSound will give an alert in both cases (in the first one use var cat = new Cat(4, "meow"))
23rd Jul 2017, 6:52 AM
The Coding Sloth
The Coding Sloth - avatar
+ 2
an object in JS is a variable with properties: var cat = {legs: 4, sound:"meow"}; cat is an object in this example and it has 2 properties, 4 legs and a sound it makes. A constructor is a function used to create an object, so if we want a constructor for our cat it could look like this: function Animal(legs, sound) { this.legs = legs; this.sound = sound; } now we can use: var cat = new Animal(4, "meow"); and we have the same object as the first example
23rd Jul 2017, 6:21 AM
The Coding Sloth
The Coding Sloth - avatar
+ 1
Thank u for ur explanation....
23rd Jul 2017, 6:32 AM
Vengatesharavinth P
Vengatesharavinth P - avatar
+ 1
what about object medhods??
23rd Jul 2017, 6:46 AM
Vengatesharavinth P
Vengatesharavinth P - avatar