Arrays and Objects in Js: 11. Creating a new object


#1

here is the link to the lesson I am on: https://www.codecademy.com/courses/javascript-beginner-en-9Sgpi/2/3?curriculum_id=506324b3a7dffd00020bf661

Here is my code:
var me = {
me.name = "Kat",
me.age = 13,
};

It's talking about object constructors, but I don't really understand what those are and how they work, can someone please help? thanks.


#2

@krazykodekat

---------First------------

Let's start with an example. We all know that a car is an object. A car has properties like weight and colors and all have methods like start and stop. All cars have properties but properties values differ from car to car. All cars have same methods but can be called at different time.

--------Object Properties-------------

You can create an object with either the constructor notation or the literal notations. We store the object in a variable

Example of constructor notation

var objectName = new Object(); // here we declare a new object
objectName.properties = value; // we give him property and value either using the 
objectName['properties'] = value; // dot notation or brackets notation

Example of literal notation

var objectName ={ // we declare a new object
properties: values, // we give him properties and values
properties: values // when you have more than one property/value
}; // you must separate it with a comma

To access to the property value, you use the dot notation or bracket notations like this:

objectName['propertyName']; // using the bracket notations
objectName.propertyName; // using the dot notations

--------Object Methods-------------

To create methods for an object, we use the following syntax:

var objectName ={ // we create a method for the object inside of the object
methodsName: function(optional parameters) { // we give its name and assign as value a function
// the code runs here
}
};

To access to methods we can use the dot notation or the bracket notation:

objectName.methodName(); // here using dot notations
objectName['methodName']; // here using brackets notations

---------More reference can be found-------------

  1. W3Schools: http://www.w3schools.com/js/js_objects.asp
  2. Developper Mozilla Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Hope this clarifies your understanding!:wink:


#3

thanks so much!! This really gives me a clear understanding about Objects!!! :grinning:


#4

It is a very nice explanation, great dude... but you didn't respond the answer.
Thanks


#5

What do you mean? I clearly asked how objects worked, not the answer to the code.


#6

not for you sorry.... the one who explained well,,, i.e. @miniapple8888


#7

I have a question should the brakets in var me = new Object(); be always empty.