Good afternoon. In C#, I create a class, then from this class I create a class variable (or object). And if I work with collections, then I add my new classes to the collection.
class person{
int id;
string name;
int age;
}
person myPerson = new person();
List<person> people = new List<person>();
people.add(myPerson);
As I understand it, in Javascript it happens in a different way. Here they do not like to create classes first, but directly add an object with data directly to the collection.
Tell me how Javascript is used to work with its own data types. What is the approach used?
CodePudding user response:
You can work in JS (since ES6) exactly as in C# :
C# code :
class person{
int id;
string name;
int age;
}
person myPerson = new person();
List<person> people = new List<person>();
people.add(myPerson);
JS code :
class Person
{
constructor(id, name, age)
{
this.id = id;
this.name = name;
this.age = age;
}
}
myPerson = new Person("p1", "Tom", 54);
people = [];
people.push(myPerson);
Hope it helps ! :)
CodePudding user response:
C# is a strongly typed language, that is, you can declare a variable to be an instance of an object (or a primitive type) and then the language will throw an error if you violate this. So, a collection like this
List<person> people = new List<person>();
makes sense in C#. However, Javascript is a weakly typed language, that is, you can define a variable to be an instance of a class, but you cannot declare it. So, if you do something like this:
var myVariable = new MyClass();
then you have instantiated MyClass
in your definition, but you only declared myVariable
to be a variable.
In Javascript you can use arrays or objects as collections. Example using array:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
var myCollection = []; //creating the collection
myCollection.push(new Rectangle(2, 3)); //adding an element to a collection
myCollection.push(new Rectangle(3, 2)); //adding an element to a collection
myCollection.push(new Rectangle(4, 4)); //adding an element to a collection
myCollection.push(new Rectangle(10, 15)); //adding an element to a collection
for (let rectangle of myCollection) {
console.log(`${rectangle.width} x ${rectangle.height}`);
}
Example using object
let myCollection = {
'first': 'a',
'second': 'b',
'third': 'c'
}
myCollection.fourth = 'd';
for (let key in myCollection) console.log(`${key} is ${myCollection[key]}`);
In Javascript, class
is a syntactic sugar for functions. Example:
function MyClass(foo, bar) {
this.myFoo = foo;
this.myBar = bar;
}
let obj = new MyClass('abc', 'def');
console.log(obj);