1

Earlier in js, we were able to do this:

var emptyObj = {};

this created an empty object, but this object is an instance of which class or is there something that I'm missing? The concept of classes has been introduced in es6 then how were we able to define objects in es5 and earlier without the presence of a class (as objects are nothing but an instance of a class)? Please clarify!

5

1 Answer 1

6

...but this object is an instance of which class...?

Object, but keep reading...

The concept of classes has been introduced in es6...

Not really. ES2015 (aka "ES6") adds class syntax, but it doesn't add the concept of classes. ES5 and ES2015 both have the concept of classes (groups of objects with commonality), and neither has classes in the sense of class-based OOP languages like Java or C#.

JavaScript has prototypical inheritance, and overlaid on that it has constructor functions. When you use new with a constructor function, new creates an object that uses the object referenced by the function's prototype property as its prototype.

var emptyObj = {};

does the same thing

var emptyObj = new Object();

does, assuming that Object there has its default value.

ES2015's class syntax just makes it easier to define constructors and the object assigned to their prototype property. This ES5 code

function Foo(value) {
    this.value = value;
}
Foo.prototype.squared = function() {
    return this.value * this.value;
};

and this ES2015 code:

class Foo {
    constructor(value) {
        this.value = value;
    }
    squared() {
        return this.value * this.value;
    }
}

both create a Foo constructor function and an object assigned to Foo.prototype with squared on it. There are a couple of minor differences (mostly to support super), but it's still the same prototypical inheritance with constructor functions overlaid on it whether in ES5 or ES2015.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.