Jump to content

Recommended Posts

I need a Wrapper or a Class that can control the Max Length of an Array on setting a value...  It might be possible with a Prototype too, which is fine...

let myArray = new ArrayClassThing();

myArray.setMax = 50; // should be a const value set in Constructor or Prototype

myArray[50] = "Foo";  // This should work fine, I know index starts at 0, but I am not using 0 so total of 50
myArray[51] = "Bar";  // Need to do nothing

Javascript is different than Ruby where you can use special characters to define Getter and Setter methods:

# Ruby Code
class Array_Wrapper
  def initialize
    @data = []
  end
  # Getter
  def [](id)
    if id <= 50 and @data[id]
      return @data[id]
    end
  end
  # Setter
  def []=(id,value)
    if id <= 50
      @data[id] = value
    end
  end               

As far as I understand, cant use a "[]" as a Getter or Setter Method, and I need something that can do exactly that, just to control a Static Maximum

 

Can anyone help out with this?

Link to comment
https://forums.phpfreaks.com/topic/312672-array-wrapper-or-class/
Share on other sites

Im gonna need a lot of classes and trying to keep code clean and minimal.  Proxies just make a basic class look... well, messy.

 

  What about something like this?

 

  class Game_Var {
    constructor(){
      this._data = [null];
      const _self = this;
      
      _self.__proto__.value = function(id){
        // do stuff here;
      }
    }
  }

How do I define Getters and Setters in this?  Or something similar...

Edit: Let me be clear here.  I dont want to call the property name from the outside, only the class instance and braces:

//... some class definition

var foo = new MyClass();

foo[1] = "bar";

if (foo[1] == "bar") alert("ok here");

 

Edited by Heretic86
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.