Spherical forums

Sphere Development => Sphere General => Topic started by: casiotone on May 26, 2013, 12:06:27 pm

Title: Object-orienting Sphere's API
Post by: casiotone on May 26, 2013, 12:06:27 pm
Not sure if this has been covered, but I came to the realisation that replacing the Load* functions is quite simple with low overhead...

example (in coffeescript)
Code: [Select]

class Color
constructor: (r, g, b, a=255) ->
color = CreateColor r, g, b, a
color.constructor = c
return color

white = new Color 255, 255, 255


In JS you can return another object from a constructor, so all we have to do is fix the constructor of Sphere's object. The fixed object is still accepted by the API, and instanceof works.

in JS
Code: [Select]
    function Color(r, g, b, a) {
      var color;
      if (a == null) {
        a = 255;
      }
      color = CreateColor(r, g, b, a);
      color.constructor = Color;
      return color;
    }
Title: Re: Object-orienting Sphere's API
Post by: N E O on May 28, 2013, 02:27:37 pm
You say "instanceof works" but what does it report for such an object?

Other than my small confusion regarding that (I'm probably simply brainfarting and it's probably "[Object Color]" all along), I agree that this is a great and simple method to wrap Sphere's native object creators :)
Title: Re: Object-orienting Sphere's API
Post by: casiotone on May 29, 2013, 04:19:00 pm

You say "instanceof works" but what does it report for such an object?

Other than my small confusion regarding that (I'm probably simply brainfarting and it's probably "[Object Color]" all along), I agree that this is a great and simple method to wrap Sphere's native object creators :)

specifically,
Code: [Select]

var color = new Color(255, 255, 255); // actually returns a Sphere color object
color instanceof Color // true


One other thing you can do that also (appears) to work:

Code: [Select]

    function Color(r, g, b, a) {
      var color;
      if (a == null) {
        a = 255;
      }
      color = CreateColor(r, g, b, a);
      color.constructor = Color;
      color.__proto__ = Color.prototype;
      return color;
    }

    Color.prototype.grayscale = function() { return (this.red + this.green + this.blue) / 3; }


you can actually define methods on Color's prototype that work as normal!
Title: Re: Object-orienting Sphere's API
Post by: N E O on May 29, 2013, 04:41:18 pm
Ooh! Even better, thanks! I do believe I shall sticky this topic.