user9240010
user9240010

Reputation:

What do you mean by instance in Javascript

I am having tough time understanding the meaning of Instance properties

For example in Firefox ES6 Class document it says https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Instance properties

Instance properties must be defined inside of class methods

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

I just see this as a class with constructor, so what do they mean by instance properties?

Upvotes: 1

Views: 121

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

The instance properties there are height and width:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
//  -----^^^^^^
    this.width = width;
//  -----^^^^^
  }
}

An "instance" is an object. One tends to use "instance" in relation to code using class-like syntax, but it just means object (though often the implication is "object of a particular class").

Contrast with "static" or "class" properties:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}
Rectangle.FOUR_BY_FOUR = new Rectangle(4,4);

There, FOUR_BY_FOUR is a "class/static" property. Or using the syntax proposed by the static class features proposal (currently Stage 3):

class Rectangle {
  static FOUR_BY_FOUR = new Rectangle(4,4);

  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

Upvotes: 1

Isaac
Isaac

Reputation: 12884

You can picture class as a blueprint or modelling. Using the class that you've defined in your question for explanation

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

We have a class named Rectangle as a "blueprint" or design. Now we can create many individual instance/object by defining their own instance properties, base on this "blueprint"/Rectangle

let bigRectangle = new Rectangle(300,300);
let smallRectangle = new Rectangle(50,50);

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 405955

That means each instance of a Rectangle will have the properties height and width.

Later, they show how to create an instance.

const square = new Rectangle(10, 10);

Here, square is an instance of a Rectangle whose height and width properties are both initialized to 10.

Upvotes: 0

Related Questions