Skip to content

Instantly share code, notes, and snippets.

@dotja
Created January 14, 2021 22:36
Show Gist options
  • Save dotja/9a0d4d6d5f6e491eb9369b05689dc9ac to your computer and use it in GitHub Desktop.
Save dotja/9a0d4d6d5f6e491eb9369b05689dc9ac to your computer and use it in GitHub Desktop.
An intro to OOP in Javascript
// a simple object literal
var person = {
name: 'Alex',
hi: function() {
alert("Hi! I'm " + this.name + " .");
}
}
// check the properties and methods
person.name;
person.hi();
// this object is an instance of the Object type
person instanceof Object;
// another way to create an object
var person = new Object();
person.name = 'Alex';
person.hi = function() {
alert("Hi! I'm " + this.name + " .");
};
// another way to create an object
var person = new Object({
name: 'Alex',
hi: function() {
alert("Hi! I'm " + this.name + " .");
}
});
// creating a custom type
function Person(name) {
this.name = name;
this.hi = function() {
alert("Hi! I'm " + this.name + " .");
};
}
// create an instance pf Person
var person = new Person('Alex');
// check the constructor
person.constructor;
// using the constructor as a function i.e. without "new"
var person = Person('Alex');
person.name
name
// constructor Vs. prototype
function Person(name) {
this.name = name;
this.constructor_list = [];
}
Person.prototype.prototype_list = [];
obj1 = new Person('one');
obj2 = new Person('two');
obj1.constructor_list.push('test1');
obj2.constructor_list;
obj1.prototype_list.push('test2');
obj1.prototype_list;
obj2.prototype_list;
// inheritance using call()
function Person(first, last) {
this.name = first + last;
}
function Staff(first, last, position) {
Person.call(this, first, last);
this.position = position;
}
// inheritance with __proto__
let a = {
'a': 1,
hi: function() {return this.a;}
};
a.__proto__;
let b = {
'b': 1,
__proto__: a
};
b.__proto__;
b.hi();
// inheritance using create()
let a = {
'a': 1,
hi: function() {return this.a;}
};
let b = Object.create(a);
// inheritance using "class"
class Person {
constructor(name) {
this.name = name;
}
hi() {
console.log("Hi!");
}
}
person = new Person('Alex');
person.hi();
// create a subclass
class Staff extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
}
let staff = new Staff('Alex', 2);
staff.hi();
staff.grade;
staff.name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment