How many ES6 classes are different from the ES5 style?

I am such a person who needs to know everything in the depths ... So, I went through many taught subjects, and I put my foot in the depths of the prototype heritage.
I have a clear idea of ​​how this works in ES5 (each function has this special prototype property that points to the object on which it is based. This object has a .constructor property that points to a function, etc.) .

So now let's look at an ES5 example:

function Bunny(name) {
    this.name = name
}

Bunny.prototype.sayName = function() {
    console.log('Im',this.name)
}

This is pretty clear: the Bunny function receives an argument namethat will be assigned to the new object.

The next line adds a function to the function prototype, which will return the current name.

Now let's see the ES6 class:

class Fox{
    constructor(name){
        this.name = name;
    }

    sayName() {
        console.log('Im', this.name)
    }
}

: Constructor Bunny. sayName , sayName Bunny.
:

let bunny = new Bunny('Henry');
let fox = new Fox('Jerry');

, :

console.log(Object.getPrototypeOf(bunny))
console.log(Object.getPrototypeOf(fox))

?

//using repl.it - ES6
{ sayName: [Function] }
{}

?

, , sayName Bunny. :

function Bunny(name) {
    this.name = name

    //Warning - Bad practice ahead! 
    this.sayName = function() {
        console.log('Im',this.name)
    }
}

:

//using repl.it - ES6
{}
{}

, :

console.log(bunny.hasOwnProperty('sayName'))
console.log(fox.hasOwnProperty('sayName'))

, fox sayName , , . - ? ?

+4
1

ES6 , ES6 , .

. :

const obj = new (class {method() {}});

console.log(Object.getPrototypeOf(obj)); // {}
console.log(typeof Object.getPrototypeOf(obj).method); // function
Hide result

ES5 , , . , ES6, Object.defineProperty():

const TestClass = function TestClass() {};
Object.defineProperty(TestClass.prototype, 'method', {
  value: function() {},
  writable: true,
  enumerable: false,
  configurable: true,
});
const obj = new TestClass();

console.log(Object.getPrototypeOf(obj)); // {}
console.log(typeof Object.getPrototypeOf(obj).method); // function
Hide result

fox.hasOwnProperty('sayName') false, hasOwnProperty() , sayName - . , in: 'sayName' in fox true.


. MDN.

+7

Source: https://habr.com/ru/post/1660517/


All Articles