In the last weeks of CS169.2x class, discussion touched upon Javascript and first-class objects. Javascript functions are first-class object, which means that they can be passed as arguments to other functions, returned as values from other functions, be a part of a data structure or assigned as variables.
What does this look like? A simplified example based on the lectures/the book will look like this:
var Square = function(side){
this.side = side;
this.result = function(){
return this.side * this.side;
}
}
Square works as a constructor and creates a new object when we call it using the word new:my_square = new Square(2);
We can then call the
result function like this (keeping parenthesis is important):my_square.result();
As such, this creates a new object whose properties are initialized in the constructor, and we then can return a value from the
result function.There is much more to this, of course. This is a short explanation based solely on my understanding of the CS169.2x materials up to date. Javascript is a huge, vast land, and I am looking forward to exploring its vastness and digging further into details.
No comments :
Post a Comment