Reputation: 15004
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);
Upvotes: 2
Views: 2747
Reputation: 165971
In strict mode, this
will not refer to the window. In your example, removing the strict mode directive will cause this
to refer to window.
Since in strict mode, this
in your example is undefined
, you get an error. That's because you can't set properties on something that is undefined
.
From MDN (emphasis on the parts relevant to your situation):
First, the value passed as this to a function in strict mode isn't boxed into an object. For a normal function, this is always an object: the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this... Automatic boxing is a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is used unchanged
Upvotes: 3