Recently I've been testing out classes with ES6, I've noticed that when creating a class you cannot specify the value given by the constructor.
Previously in ES5 this was possible.
In both cases I would instantiate the class with new MyClass
The reason I want to do this is so I can return a subset of the current class with only functions on it.
My class was init with: Blah
var MyClass = function() {
this.initVar = 'Blah'
return 'My Class was init with: ' + this.initVar
}
{}
class Bob {
constructor() {
return 'hello'
}
}
The ES6 actually does not return {} but the class (constructor) object in that case. The class constructor can return objects, but not primitive values. So instead of [String] "hello" it returns [Object] Bob .
Top Alternatives to ES6 js or Apache CouchDB. It is a prototype-based, multi-paradigm scripting language that is dynamic,and supports object-oriented, imperative, and functional programming styles. ... It adds syntactic sugar inspired by Ruby, Python and Haskell in an effort to.
Once the code is executed, the constructor will return: Any valid return value, valid being only object values. The this object if there is no return statement executed with a valid value.
To declare a variable within a class, it needs to be a property of the class or, as you did so, scoped within a method in the class. It's all about scoping and variables are not supported in the scope definition of a class.
According to the Class article from the TC39 web site, the ES6 class syntax has an implicit constructor function that is called if no such function is provided in the class definition.
This can be overridden by providing your own constructor and returning whatever object you want, e.g.:
class Bob {
constructor(name) {
return {hi: name}; // returns an object other than *this*.
}
}
In action:
var bob = new Bob('bob');
console.log(bob.hi); // 'bob'
To extend the class, you can do:
class Bill extends Bob {
}
However extends also has an implicit constructor, so it will return a new instance of Bill that inherits from Bob.prototype. Since hi was defined in the constructor and not inherited, you get:
var bill = new Bill('bill');
console.log(bill.hi); // undefined
To initialise Bill the same as Bob, provide a constructor that calls super. This call also changes the this object of Bill to the value returned by super, e.g.
class Bill extends Bob {
constructor(name) {
super(name);
}
}
Now:
var bill = new Bill('bill');
console.log(bill.hi); // bill
Also worth noting that the body of a classDeclaration is always strict mode code.
As a runnable snippet:
class Bob {
constructor(name) {
return {hi: name}; // returns an object other than *this*.
}
}
var bob = new Bob('bob');
console.log(bob.hi); // 'bob'
class Bill extends Bob {
constructor(name) {
super(name);
}
}
var bill = new Bill('bill');
console.log(bill.hi); // bill
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