If I use strict mode the following code does not work. It fails on the this.bar = ‘foobar’; line. Why is this so? How can I make an object property in strict mode?
<html>
<body>
<script>
"use strict";
var foo = (function () {
this.bar = 'foobar';
return this;
}());
alert(foo.bar);
</script>
</body>
</html>
edit:
Thanks to James Allardice for pointing out the problem.
I was erroneously thinking that the self executing function was creating an object but it isn’t. I needed to do one of the following instead:
"use strict";
var foo = new function () {
this.bar = 'foobar';
};
alert(foo.bar);
or (this one JSLint likes better)
"use strict";
var foo = (function () {
var obj = {};
obj.bar = 'foobar';
return obj;
}());
alert(foo.bar);
In strict mode,
thiswill not refer to the window. In your example, removing the strict mode directive will causethisto refer to window.Since in strict mode,
thisin your example isundefined, you get an error. That’s because you can’t set properties on something that isundefined.From MDN (emphasis on the parts relevant to your situation):