[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

OOP and first class functions question

bit-naughty

6/2/2014 6:41:00 PM

If I have var x = function() { whatever}, and I then say var p =x , can I then say var newobj = new p(); ? And then will everything inside x be available like eg. newobj.method?



Thanks.
2 Answers

Scott Sauyet

6/2/2014 7:26:00 PM

0

bit-naughty@hotmail.com wrote:
> If I have var x = function() { whatever}, and I then say var p =x ,
> can I then say var newobj = new p(); ? And then will everything
> inside x be available like eg. newobj.method?

Yes.

var Rectangle = function(w, h) {this.width = w; this.height = h;};
Rectangle.prototype.area = function() {return this.width * this.height;};
var Rect = Rectangle;
var box = new Rect(3, 5);
box.area(); //=> 15 // It works!

The function is a first-class item in the Javsacript ecosphere. The variable
`Rectangle` used to hold a reference to that function is just that. You can
add another reference, such as `Rect`, and that function will still behave
as before. You could even then reset the original reference, and the new one
would continue to function:

Rectangle = null;
var r = new Rectangle(2, 6); //=> TypeError
var r = new Rect(2, 6);
r.area(); //=> 12

HTH,

-- Scott

bit-naughty

6/3/2014 1:03:00 PM

0

Thanks, Scott! :)