javascript - Undefined Property after new object construction using 'this' in constructor with self-executing function inside Object.defineProperty -
i'm attempting use typescript-like structure emulate enumeration in self-executing function 'value:' property. checked on examples of ecmascript5 / crockford object.defineproperty() use in constructor (using 'this') not find much. far can tell, self-executing function should fill both objects 10 properties, , closure correct ('this' not window object). here's design pattern:
var player = {}; var foo = function () { this.levelindex; object.defineproperty(this, 'levelindex', { value: (function (levelindex) { levelindex[levelindex.one = 0] = 'one'; levelindex[levelindex.two = 1] = 'two'; levelindex[levelindex.three = 2] = 'three'; levelindex[levelindex.four = 3] = 'four'; levelindex[levelindex.five = 4] = 'five'; // setup player object properties of levelindex // before becomes non-enumerable: (var in levelindex) { object.defineproperty(player, i, { value: isnan(levelindex[i]) ? 'level_' + levelindex[i] : levelindex[i], enumerable: false }); alert(player[i]); //<-- level_one, level_two, level_three, level_four, level_five, 0, 1, 2, 3, 4 } alert('window? : ' + === window); //<-- false })(this.levelindex || (this.levelindex = {})), writable: false, enumerable: false, configurable: false }); }; var foo = new foo(); alert(player.one); //<-- 0 alert(foo.levelindex); //<-- undefined alert(foo.levelindex.one); //<-- uncaught typeerror: cannot read property 'one' of undefined
why foo.levelindex
undefined here?
edit: fixed return levelindex;
added anonymous function call.
any comments on design pattern or suggestions improvement welcome!
you're calling anonymous function plain function call, value of this
undefined
in strict mode, or global object (window
) otherwise. won't reference object literal you're defining.
the first line of "foo" function looks little suspicious:
this.levelindex;
that have no effect on anything; specifically, not cause there property named "levelindex" created on object referenced this
.
edit — also, more @ you're doing, it's pretty clear why "levelindex" property ends undefined
: object literal has "value" property that's set return value of anonymous function call. anonymous function, however, has no return
statement, call object.defineproperty
involves property object "value" property set undefined
. if add
return levelindex;
to end of anonymous function, (might) work. (i think would.)
Comments
Post a Comment