function constructor - it uses an operator new to create objects using the function you created.
syntax 1: (The object is implicit. It uses the this keyword.)
function Name(a, b){
this.a = a;
this.b = b;
}
Equivalent 1:
function Name(a, b){
let obj = {};
this.a = a;
this.b = b;
return obj;
}
Invoking syntax 1:
let x = new Name("hello", "world");
Equivalent 2:
function Name(a, b){
return {a, b};
}
Equivalent 3:
function Name(a, b){
return {
a : a,
b: b
}
}
====================
function Book(id, title, author, published){
this.id = id;
this.title = title;
this.author = author;
this.published = published;
}
function displayBookInfo(){
document.writeln('id: ${this.id} - title: ${this.title} - author: ${this.author} - published: ${this.published}');
}
function AnotherBook(id, title, author, published){
return {id, title, author, published}
}
function getBookInfo(){
let book1 = new Book(1, "Slime", "slimy", 2019);
book1.displayBook1 = displayBookInfo;
book1.displayBook1();
let book2 = new Book(2, "Tooth", "toothy", 2022);
book2.displayBook2 = displayBookInfo;
book2.displayBook2();
let book3 = new AnotherBook(3, "The Singer", "musician", 2000);
book3.displayBook3 = displayBookInfo;
book3.displayBook3();
}
====================
HTML
getBookInfo()
Result:
id: 1 title: Slime author: slimy published: 2019 id: 2 title: Tooth author: toothy published: 2022 id: 3 title: The Singer author: musician published: 2000
YOU ARE READING
Javascript Programming
RandomI am just documenting things what i learned online in here. I do express things in my own words. And I create my own program samples which serves as my practice. I do this so that when someday I would need some notes to review, I can just visit in h...
