Monday, July 20, 2020

JavaScript, prototype, constructor. Things you will not attempt in other languages

function Foo() {}

// this is used to simulate OOP's static method 
Foo.baz = function () {
    console.log('baz');
};
// this is used to simulate OOP's instance method
Foo.prototype.bar = function () {
    console.log('bar');
};

console.log('fighter');
Foo.fighter = function () {
    this.baz();
    // this.bar(); // TypeError: this.bar is not a function

    this.prototype.bar();
    this.prototype.constructor.baz();
};
Foo.fighter();

console.log('warrior');
const great = new Foo();
great.warrior = function () {
    this.bar();
    // this.baz(); // TypeError: this.baz is not a function

    this.constructor.baz();
    this.constructor.prototype.bar();
};
great.warrior();

fighter
baz
bar
baz
warrior
bar
baz
bar

No comments:

Post a Comment