Skip to content

Instantly share code, notes, and snippets.

@ArunHub
Created December 27, 2019 11:28
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 ArunHub/e7987df0229a7617ae4598ad19f3dd3a to your computer and use it in GitHub Desktop.
Save ArunHub/e7987df0229a7617ae4598ad19f3dd3a to your computer and use it in GitHub Desktop.
class Dog {
constructor() {
this.name = "woof";
}
bark() {
console.log(this.name)
}
}
var dd = new Dog()
dd.bark();
$('button').click(dd.bark)
// does not work
$('button').click(dd.bark.bind(dd))
// works
$('button').click(()=>dd.bark())
// works using arrow function
// so instead of creating objects, create factories
const Dog1 = ()=>{
const name = "woof";
return {
bark: ()=>console.log(this.name)
}
}
const sniff = Dog1();
sniff.bark(); //works
$('button').click(sniff.bark)
// creating object
// let animal = {};
// animal.name = "duster";
// animal.energy = "10";
// animal.bark = function(en) {
// console.log('yessssss', this.name);
// this.energy = this.energy + en;
// }
// animal.play = function(pl) {
// this.energy -= pl;
// }
// animal.play(10);
// functional intantiation
// function Animal(name, energy) {
// let animal = {};
// animal.name = name;
// animal.energy = energy;
// animal.bark = function(en) {
// console.log('yessssss', this.name);
// this.energy = this.energy + en;
// }
// animal.play = function(pl) {
// this.energy -= pl;
// }
// return animal;
// }
// const leo = Animal('Leo', 20);
// functional intantiation with shared methods
// let animalMds = {
// bark(en) {
// console.log('yessssss', this.name);
// this.energy = this.energy + en;
// },
// play(pl) {
// this.energy -= pl;
// }
// }
// function Animal(name, energy) {
// let animal = {};
// animal.name = name;
// animal.energy = energy;
// animal.play = animalMds.play;
// animal.bark = animalMds.bark;
// return animal;
// }
// const leo1 = Animal('Leo', 25);
// leo1.play(55);
const parent = {
name: 'arun',
age: 27
}
const child = Object.create(parent);
child.name = "kumar";
console.log('chi',child.name);
console.log('chi',child.age);
// functional intantiation with shared methods
const animalMds = {
bark(en) {
console.log('yessssss', this.name);
this.energy = this.energy + en;
},
play(pl) {
this.energy -= pl;
}
}
function Animal(name, energy) {
let animal = Object.create(animalMds);
animal.name = name;
animal.energy = energy;
return animal;
}
const snoop = Animal('snoop', 25);
snoop.play(55);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment