Created
October 12, 2021 17:10
-
-
Save juan-reynoso/e4ac352b4845edcfb96fcd009f13338b to your computer and use it in GitHub Desktop.
Creating a JavaScript Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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