Javascript specific knowdlege

This week-end I found on Twitter an Javascript escape contest: http://escape.alf.nu. At level 9 there’s need of specific js knowledge:

1) As you know, you can call an object method with: obj.method() or with obj[‘method’](), so using the object like an array, ad accessing to it with a string, so you should also do this: obj[‘meth’+’od’]() and you will have the same result.

2) To transform anything to a string,in js (as in java, etc..), you can type this: obj+””: some examples:

  • 1+”” -> “1”
  • []+”” -> “”
  • [1,2]+”” -> “1, 2”
  • {}+”” ->”[object Object]”
  • false+”” -> “false”

3)You can use bitwise operators as: !, ~ before “[]”, “{}”, “1,2..”, some examples:

  • ![] = !{} -> false (boolean value)
  • ~[] = ~{} -> -1 (number value)

4)Every function in JavaScript is actually a Function object [mdn] and an object instance in Javascript has many default properties: constructor, __proto__ and methods: toString(), valueOf().

The property constructor:Returns a reference to the Object function that created the instance’s prototype” [mdn], so if you do this: ((“0”)[“constructor”]) to have the reference to String object, because “0” is a string; and with (0[“constructor”]) you have a reference to Number object, and so on!

If you can get the reference to Function object, you can use it as eval function, so you can pass to it a string to be interpreted:
var f = new Function(“alert(1)”); f(); //this will show an alert
I remember you, that you can do also this: var f = alert; f(1); to call an ‘alert
(1)’

Came back to (0[“constructor”]): it is referenced to Number Object, so you can see (0[“constructor”]) as Number. As you could see in the Dom inspector of your browser, there’re many methods for Number object:

  • you can access to Number.parseInt in this way: (0[“constructor”][‘parseInt’])(“10”). This is like: Number.parseInt(“10”);
  • you can use Function object with the method ‘constructor’ of any object, example: var f = Number.constructor(“alert(1)”); f(); in this way you can call ‘alert(1)‘; an example of this technique can be found on jjencode.

That’s all! Now you have to bases knowledge to pass this level!