On Dec 9, 5:27 am, Nick Morgan <[email protected]> wrote:
> Here's an example:
>
> function makeAnObject() {
> var outerThis = this;
>
> return {
> a: this,
> b: function () {
> return this;
> }
> };
>
> }
>
> When you call makeAnObject as a function, the `this` that `a` is set to is
> the same as `outerThis` (which is the global object). The `this` inside `b`
> will be the new object.
Not necessarily, it still depends on how the function assigned to b is
called:
function makeAnObject() {
var outerThis = this;
return {
a: this,
b: function () {
'use strict';
return this;
}
};
}
// Expected case
var x = makeAnObject();
alert(x.b() == x); // true;
// Assign to variable
var y = x.b;
alert(y() == x); // false;
// Call from a different context and test strict mode
function strictly() {
return y();
}
alert(typeof strictly() == 'undefined'); // true in ES5
// false in ES3
// Create a new object
var z = {b: x.b};
alert(z.b() == x); // false;
// Force assignment to expected object
alert(z.b.call(x) == x); // true
--
Rob
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]