Skip to main content

News

Topic: Object-orienting Sphere's API (Read 2340 times) previous topic - next topic

Object-orienting Sphere's API
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;
    }

  • N E O
  • [*][*][*][*][*]
  • Administrator
  • Senior Administrator
Re: Object-orienting Sphere's API
Reply #1
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 :)

Re: Object-orienting Sphere's API
Reply #2

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!

  • N E O
  • [*][*][*][*][*]
  • Administrator
  • Senior Administrator
Re: Object-orienting Sphere's API
Reply #3
Ooh! Even better, thanks! I do believe I shall sticky this topic.