DEV Community

Tomohiro Yanagi
Tomohiro Yanagi

Posted on

This is why you cannot mixi'n ES2015 class's methods

class Hoge {
    constructor() {
        this.hoge = 'hoge';
    }
    static log() {
        console.log(this.hoge);
    }
    logger() {
        console.error(this.hoge);
    }
}

function Fuga() {
    this.fuga = 'fuga';
}

Fuga.log = function () {
    console.log(this.fuga);
};

Fuga.prototype.logger = function () {
    console.error(this.fuga);
};

const hoge = new Hoge();
const fuga = new Fuga();
const hogeExt = $.extend({}, new Hoge());
const fugaExt = $.extend({}, new Fuga());
const hogeExtD = $.extend(true, {}, new Hoge());
const fugaExtD = $.extend(true, {}, new Fuga());
const hogeObj = Object.assign({}, new Hoge());
const fugaObj = Object.assign({}, new Fuga());

console.log('-------log----------');
console.log(Hoge.log);       // ƒ log() {console.log(this.hoge);}
console.log(Fuga.log);       // ƒ () {console.log(this.fuga);}
console.log(hogeExt.log);    // undefined
console.log(fugaExt.log);    // undefined
console.log(hogeExtD.log);   // undefined
console.log(fugaExtD.log);   // undefined
console.log(hogeObj.log);    // undefined
console.log(fugaObj.log);    // undefined

console.log('------logger-------');
console.log(hoge.logger);      // ƒ logger() {console.error(this.hoge);}
console.log(fuga.logger);      // ƒ () {console.error(this.fuga);}
console.log(hogeExt.logger);   // undefined   
console.log(fugaExt.logger);   // ƒ () {console.error(this.fuga);}   
console.log(hogeExtD.logger);  // undefined   
console.log(fugaExtD.logger);  // ƒ () {console.error(this.fuga);}
console.log(hogeObj.logger);   // undefined   
console.log(fugaObj.logger);   // undefined

console.log('------description-------');
const description = Object.getOwnPropertyDescriptor
console.log(description(hoge, 'logger'));         // undefined
console.log(description(fuga, 'logger'));         // undefined
console.log(description(hogeExt,'logger'));       // Error
console.log(description(fugaExt, 'logger'));      // {writable: true, enumerable: true, configurable: true, value: ƒ}
console.log(description(hogeExtD,'logger'));      // Error
console.log(description(fugaExtD, 'logger'));     // {writable: true, enumerable: true, configurable: true, value: ƒ}
console.log(description(hogeObj,'logger'));       // Error
console.log(description(fugaObj, 'logger'));      // undefined

console.log(
    'hoge.__proto__',
    Object.getOwnPropertyDescriptor(hoge.__proto__, 'logger')
);
// {writable: true, enumerable: false, configurable: true, value: ƒ}    //this is reason
console.log(
    'fuga.__proto__',
    Object.getOwnPropertyDescriptor(fuga.__proto__, 'logger')
);
// {writable: true, enumerable: true, configurable: true, value: ƒ}     //it's ok.

Top comments (0)