Methods

  • Updated

Methods are added to a ScriptObject instance when it’s created; they can also be added after

the instance is created.

Valid method names follow the rules for identifier naming, outlined above.

Methods can either return a value (using the return keyword) or not. They can also return the value null.

Here’s an example of creating a new method and then calling it:

var x = {};
x.ComputeSimpleInterest = function ( balance, rate ) { return balance * ( rate / 100 ); }; 
var y = x.ComputeSimpleInterest( 1000, 1.2 );	// y == 12

Built-in

ScriptObject instances have a number of built-in methods:

Method Name Return type Arguments Description
HasMember Boolean memberName Returns true if instance has member with given name, otherwise false
RemoveMember <none> memberName Removes member from instance; does nothing if memberName not a member of the instance
Copy ScriptObject <none> Makes a copy of this instance (recursively copies child ScriptObject references, other refs obey CLR ref-type/value- type semantics)

Adding your own

Methods can be added to a ScriptObject instance at any time during its lifetime:

var x = {};

x.ComputeSimpleInterest = function ( balance, rate ) { return balance * ( rate / 100 ); }; 
var y = x.ComputeSimpleInterest( 1000, 1.2 );	// y == 12
var z = { GetName : function () { return 'Fred'; } }; 
var name = z.GetName(); // z == ‘Fred’

Note that method overloading is not supported; all methods must have a name unique to the instance in question.

Methods can be assigned from function references:

var compute = function ( balance, rate ) { return balance * ( rate / 100 ); }; 
var x = {};
x.ComputeSimpleInterest = compute;

var y = x.ComputeSimpleInterest( 1000, 1.2 );	// y == 12

The special keyword this is used to reference the parent ScriptObject instance in a member method implementation:

var x = { FirstName : "Joe", LastName : "Blow" };

x.GetFullName = function () { return this.FirstName + " " + this.LastName; }; 
var y = x.GetFullName();	// y == ‘Joe Blow’

Calling missing methods

As a dynamic language, irScript allows you to call methods that might not exist on a given ScriptObject instance.

The default behavior in this case is to raise an error indicating that the requested method doesn’t exist. However, you have the ability to define a missing method handler to be called instead:

var x = { op_MissingMethod : function ( name, originalArgs )
{
if( name == 'DoWork' )
{
return 'some value';
}
else
{
return originalArgs.Count;
}
};
};

var a = x.DoStuff();	// a == 0

var b = x.DoWork( 45, 'blah', {} );	// b == ‘some value’

When used, op_MissingMethod is assigned a function that accepts two parameters (the name of the missing property, and a collection of all parameters from the original call); this function can return a value, but is not required to.

Was this article helpful?

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.