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:
- chmod 755 test.js
- ./test.js
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.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects
var a = {"key":"A value"};
var b = {};
b.__proto__ = a; // set a as prototype of b . b inherits a
/*var b = Object.create( a );*/
b.other="aaaa";
if( ! b.hasOwnProperty('key') ) print( "b doesn't have own property key" );
if( b.hasOwnProperty('other') ) print( b.other );
if( a.hasOwnProperty('key') ) print( a['key'] );
if( a.hasOwnProperty('other') ) print( a['other'] );
b.key='Other Value'; // b has own key "key" and a has also key "key" with different value
print('\nkeys in object a');
for(var key in a){
print( key ,'->' , a[key] );
}
print('\nKeys in object b');
for(var key in b){
print( key ,'->' , b[key] );
}
print('Value for key in prototype of b' , b.__proto__.key );
//-------
print();
function f(){
this.propx='asdf';
this.fn=function(){print("aaaa");};
this.nr=123.4;
}
f.prototype.protoFn=function(){ print("bbb"); };
var x = new f();
print('x instance of f ' , x instanceof f);
print('x is type of ' + typeof f);
print('x instance of object ' , x instanceof Object);
print('x instance of Array ' , x instanceof Array);
for(var key in x){
print( key ,':' , x[key] , x.hasOwnProperty(key) , typeof x[key] );
}
print( JSON.stringify( x ) );