Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Property of JavaScript object?

I am wondering if this is possible in JavaScript, I want to have an Object which could contain dynamic properties.

Give an example:

function MyObject()
{
}

var myobj = new MyObject();
myobj.property1 = "something";

alert(myobj.property1); // something
alert(myobj.property2); // this should never report error, instead the property should be evaluated to null, as it has never been set. 

Is there any way to intercept property calls in JavaScript so I can proactively set a no-value property as null?

Thanks.

like image 510
Nominee Avatar asked Dec 17 '22 04:12

Nominee


1 Answers

This is about as close as you can get to achieving your goal.

Code:

var obj = {};
alert("prop: " + obj.prop);
obj.prop = "something";
alert("prop: " + obj.prop);
delete obj.prop;
alert("prop: " + obj.prop);

Behavior:

Alert: "prop: undefined"
Alert: "prop: something"
Alert: "prop: undefined"
like image 57
geowa4 Avatar answered Dec 27 '22 03:12

geowa4