I'm playing with ECMAScript6 classes.
I still don't understand why the following code :
"use strict";
class A {}
class B extends A {}
let b = new B();
console.log(b);
Displays :
A { }
Instead of :
B { }
Live Example:
(function () {
"use strict";
class A {}
class B extends A {
foo() {
}
}
let b = new B();
console.log(b);
})();
Open the console. Works only on very up-to-date browsers (such as Chrome 43+).
How can I have the expected logical output B { } on console.log ?
May I need to specify my class name to be "B" ? Is there such an option to pass, or an attribute or a function to define ?
T.J. Crowder got it : It is a referenced bug on Chrome.
Everybody, can you star this bug to increase its priority ?
https://code.google.com/p/chromium/issues/detail?id=510688
The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.
When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.
Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more. Using class inheritance, a class can inherit all the methods and properties of another class. Inheritance is a useful feature that allows code reusability.
You haven't said what browser you're using, but I figure it has to be Chrome, given the style of the output you showed and that it runs at all. (If I run that in IE11, I get [object Object] {}
instead. If I run it in Firefox, I get an error — because Firefox doesn't support class
yet.)
I can't think of any reason other than a bug in Chrome. Support for class
is very new to Chrome, it could easily be that the devtools just aren't quite handling it correctly yet. I didn't find a bug report on http://crbug.com in a quick search, you might want to file one. But you did find it.
It really should be showing B
with your code, not A
. It does with the equivalent old-fashioned way to do it:
(function() {
"use strict";
function A() {}
function B() {
A.call(this);
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
var b = new B();
console.log(b);
})();
Open the console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With