SpiderMonkey

SpiderMonkey is Mozilla's Javascript engine written in C/C++. It is used in various Mozilla products, including Firefox, and is available under the MPL2.

Example code

   1 #!/usr/bin/js
   2 function CTest(){
   3   this.counter=0;
   4 }
   5 
   6 
   7 CTest.prototype.increment=function(){
   8   this.counter++;
   9 };
  10 
  11 CTest.prototype.show=function(){
  12   putstr(this.counter);
  13   putstr("\r\n");
  14 };
  15 
  16 var c = new CTest();
  17 var d = new CTest();
  18 c.increment();
  19 c.increment();
  20 c.increment();
  21 c.show();
  22 
  23 d.increment();
  24 d.increment();
  25 d.show();

Run it with:

SpiderMonkey is installed on Slackware 14.

Windows binary

Example of prototype/inheritance

When it comes to inheritance, Javascript only has one construct: objects. Each object has an internal link to another object called its prototype (proto).

Javascript objects are dynamic "bags" of properties (referred to as own properties). JavaScript objects have a link to a prototype object.

   1 // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects
   2 var a = {"key":"A value"};
   3 var b = {};
   4 b.__proto__ = a; // set a as prototype of b . b inherits a 
   5 /*var b = Object.create( a );*/
   6 b.other="aaaa";
   7 if( ! b.hasOwnProperty('key') ) print( "b doesn't have own property key" );
   8 if( b.hasOwnProperty('other') ) print( b.other );
   9 
  10 if( a.hasOwnProperty('key') ) print( a['key'] );
  11 if( a.hasOwnProperty('other') ) print( a['other'] );
  12 
  13 b.key='Other Value'; // b has own key "key" and a has also key "key" with different value
  14 
  15 print('\nkeys in object a');
  16 for(var key in a){
  17     print( key ,'->' , a[key] );
  18 }
  19 
  20 print('\nKeys in object b');
  21 for(var key in b){
  22   print( key ,'->' , b[key] );
  23 }
  24 
  25 print('Value for key in prototype of b' , b.__proto__.key );
  26 
  27 //-------
  28 print();
  29 function f(){
  30   this.propx='asdf';
  31   this.fn=function(){print("aaaa");};
  32   this.nr=123.4;
  33 }
  34 
  35 f.prototype.protoFn=function(){ print("bbb"); };
  36 
  37 var x = new f();
  38 print('x instance of f '  , x instanceof f);
  39 print('x is type of ' + typeof f);
  40 print('x instance of object '  , x instanceof Object);
  41 print('x instance of Array '  , x instanceof Array);
  42 
  43 for(var key in x){
  44   print( key ,':' , x[key] , x.hasOwnProperty(key) , typeof x[key]  );
  45 }
  46 
  47 print( JSON.stringify( x ) );

Javascript/SpiderMonkey (last edited 2016-08-18 17:22:04 by localhost)