1

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?

2
  • Do you understand what an "instance" is…? Commented Jun 22, 2018 at 12:36
  • whatis.techtarget.com/definition/instance // These properties are individual for each individual instance of your class that you create. When you have a class person, then you want the name property of that to hold a different value for each person instance you create … Opposed to that would be a static property, one that all instances share. Commented Jun 22, 2018 at 12:36

3 Answers 3

1

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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);

Comments

Your Answer

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