I want to do this:
var person = {
name: "John",
__test__: (function() {alert(this.name)})()
}
but this.name is undefined. How to have its value then ?
Update: to make more sense, I rather want to do this ie auto-inialisation:
var person = {
name: "",
__test__: (function() {name = "john"})()
}`
‘John’ can come in real world from a mockup object, a database whatever, my point is I want to do this in a SELF-CONTAINED way not call test from an external object.
You can’t do this using an Object literal.
thisis referring topersonafter the literal is evaluated, during evaluationthisrefers to the parent scope. You could wrap the object construction in a function to be surethisrefers to the current scope (i.e. the scope of the function). Something like:Or using variables within the function scope:
Or wrap things in a more generic factory function:
And finally (not everyone will agree to this) you could create a load handler in
Object.prototype: