Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Javascript Array or Object be overridden to be callable?

I want to figure out if Array[] and Object[] can be replaced by Array() and Object(). Can a function prototype be stuck into arrays or objects prototype chain to make them callable. Basically I am looking for some thing like this:

// some magic with prototypes
????????????????

a = [1, 3, 4]
b = [1, 3, 4]

console.log(a[1]) // prints 3
console.log(b(1)) // prints 3

a[0] = -1
// same as
b(0, -1)

console.log(a[1], b(1)) // prints -1 -1

Thanks alot!

like image 951
treeform Avatar asked Oct 11 '11 20:10

treeform


People also ask

Can a JavaScript object be an array?

Array Elements Can Be Objects JavaScript variables can be objects.

Can you push an object into an array JavaScript?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.

Is array a data type in JavaScript?

Arrays are just regular objects In Javascript, there are only 6 data types defined – the primitives (boolean, number, string, null, undefined) and object (the only reference type). Arrays do not belong to this list because they are objects as well.

How many types of object in JS?

There are 6 types of objects: Object.


1 Answers

You probably don't want to do this, especially in any browser. This doesn't have a lot of nice features of Array, including efficiency. That said:

function ArrayFunction (arr) {
  var f = function s (p, v) {
    if (v !== undefined) {
      s[p] = v
    }
    return s[p]
  }

  for (var i = 0; i < arr.length; i++) {
    f[i] = arr[i]
  }

  return f
}

var a = new ArrayFunction([1, 3, 4])
var b = new ArrayFunction([1, 3, 4])

b(1, 5)
a[1] //3
b[1] //5

I originally wanted to use prototypes, but objects don't inherit callableness from their prototypes.

EDIT: Fixed above to not use arguments. This version does not allow you to set a value to undefined, but that's generally not considered a good practice anyway.

like image 126
Tamzin Blake Avatar answered Sep 20 '22 14:09

Tamzin Blake