Hands-On Functional Programming with Typescript by Remo H. Jansen

Hands-On Functional Programming with Typescript by Remo H. Jansen

Author:Remo H. Jansen
Language: eng
Format: mobi
Publisher: Packt
Published: 2019-01-30T08:25:23+00:00


Instance properties versus class properties

Because JavaScript is a dynamic programming language, we can add properties and methods to an instance of an object at runtime; and they don't need to be part of the object (class) itself:

const name = "Remo";

const surname = "Jansen";

function Person(name, surname) {

// instance properties

this.name = name;

this.surname = surname;

}

const person1 = new Person(name, surname);

person1.age = 27;

We have defined a constructor function for an object named Person, which takes two variables (name and surname) as arguments. Then we have created an instance of the Person object and added a new property named age to it. We can use a for…in statement to check the properties of person1 at runtime:

for(let property in person1) {

console.log("property: " + property + ", value: '" +

person1[property] + "'");

}

The following will be displayed in the console output:

property: name, value: 'Remo'

property: surname, value: 'Jansen'

property: age, value: 27

property: greet, value: 'function (city, country) {

let msg = "Hi, my name is " + this.name + " " + this.surname;

msg += "\nI'm from " + city + " " + country;

console.log(msg);

}'

As we can see, age has been added as a property. All these properties are instance properties because they hold a value for each new instance. If, for example, we create a new instance of Person, both instances will hold their own values:

let person2 = new Person("John", "Wick");

person2.name; // "John"

person1.name; // "Remo"

We have defined these instance properties using the this operator because, when a function is used as a constructor (with the new keyword), the this operator is bound to the object instance constructed. The preceding also explains why we can alternatively define instance properties through the object's prototype:

Person.prototype.name = name; // instance property

Person.prototype.surname = surname; // instance property

We can also declare class properties and methods (also known as static properties). The main difference between instance properties and class properties is that the value of class properties and methods are shared between all instances of an object. Class properties are often used to store static values:

function MathHelper() {

//...

}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.