Setters using VBS and constant hacks

I wasn’t gonna blog this because I couldn’t be bothered but Mario asked me if I had it documented anywhere and I guess it’s nice to have it somewhere. So I was looking to create setters in legacy browsers like IE7 and it would be nice to use them on custom objects in IE8. I came up with the following VBS hack:-

execScript("Class c\nProperty Let x(y)\nalert(y)\nEnd Property\nEnd Class\nSet obj=new c","VBScript");obj.x=1;//yeah js calls vbs 😉

Pretty cool calling VBS from JS then using a VBS object inside JS 🙂

Ok and now some constant stuff I tweeted before but I quite like so I’ll post here too. Constants are weird in JavaScript, when you think about them you think in a value that cannot change but when it comes to objects they can’t be constants for some reason. I dunno why they could be implemented quite easily by creating a Getter only object but anyway:-

//example1
const x={};x.y=123;alert(x.y)//Objects aren't constants!

//example2 (need to run separately of course
const x={};x.toString=x.valueOf=function() { return 1; };alert(x)

Finally I’ll leave you with a quiz, what is “x” equal to without running?:-

var x=1; function y() { x=3; alert(x); return; const x=2;}y()// x == ?

3 Responses to “Setters using VBS and constant hacks”

  1. Maciej Łebkowski writes:

    Well, `const` works just like `var` in this example. It defines a local variable (and it’s evaluated at the very start of the function/scope, before any other statements). The assignment would be done in the line the statement is located, but `return` terminates it early.
    It alerts `undefined`, because at that point, `x` is already initialized (as a constant), but not yet have a value. The assignment statement fails silently… because `x` is a constant, cannot be assigned to (changing `const` to `var` would change this behavior).
    And of course `x` is a local variable of `y()`, so global-scope `x` remains unchanged and equals `1`.

    Nice. ;-D

  2. Gareth Heyes writes:

    I hope you didn’t test it first, if so hello mr js hax0r 🙂 if you have a twitter account I’d be interested 😉

  3. Maciej Łebkowski writes:

    I knew the value of global scope `x` without testing. The `undefined-inner-x` part got me a little bit confused, I would guess it would equal `3` before running.
    So I got just the first part right blindfolded 🙂

    I’m @puck, but I’m not really into twitter, so its quite silent there 😀