Skip to content

Instantly share code, notes, and snippets.

@juan-reynoso
Created October 12, 2021 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juan-reynoso/e4ac352b4845edcfb96fcd009f13338b to your computer and use it in GitHub Desktop.
Save juan-reynoso/e4ac352b4845edcfb96fcd009f13338b to your computer and use it in GitHub Desktop.
Creating a JavaScript Objects
/* Creates a single object, using an object literal.
* An object literal is a list of name:value pairs
(like age:36) inside curly braces {}.
*/
let myObjectPerson = { name: 'Juan', age: 36, sayHello: function (){
console.log("Hello, I am " + this.name + " and I am " +
this.age + " years old.");}
};
myObjectPerson.sayHello();
// Creates an empty JavaScript object using new Object()
let myObjectPerson1 = new Object();
myObjectPerson1.name = "Juan";
myObjectPerson1.age = 36;
myObjectPerson1.sayHello = function (){
console.log("Hello, I am " + this.name + " and I am " +
this.age + " years old.");
};
myObjectPerson1.sayHello();
// JavaScript Object Prototypes
function Person (name, age){
this.name = name;
this.age = age;
this.sayHello = function (){
console.log("Hello, I am " + this.name + " and I am " +
this.age + " years old.");
}
}
let myObjectPerson2 = new Person("Juan", 36);
myObjectPerson2.sayHello();
/*
* A JavaScript class is not an object.
* It is a template for JavaScript objects.
*/
class Person1{
constructor(name, age){
this.name = name;
this.age = age;
}
sayHello (){
console.log("Hello, I am " + this.name + " and I am " +
this.age + " years old.");
}
}
// When you have a class, you can use the class to create objects:
let myObjectPerson3 = new Person1("Juan", 36);
myObjectPerson3.sayHello();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment