views:

55

answers:

2

let's say I have code like this:

var object1 = {};
object1.class1 = function() {
    this.property1 = null;
    this.property2 = 'ab';
}

in this case, what does 'this' stand for? object1 or class1? And whenever I want to define a class constructor inside an object, what is the best way to do it?

+2  A: 

For class1, because you can't make an object of type object1.

However, if the code would be:

function object1() {
    this.class1 = function() {
        this.property1 = null;
        this.property2 = 'ab';
    }
}

You could have:

var obj = new object1();
obj.class1();
obj.property2; // => 'ab';

var cls = new obj.class1();
cls.property2; // => 'ab';

So it could depend on context.

Mewp
That said, I have seen situations where 'this' does refer to object1. Seem that if the properties are already exist within object1, class1 turn into just a mere method. Sigh, if only there was a way I can tell for sure.
Khoi
@Khoi: No. `this` refers to the object passed as `this` to the method. If you wanted, you could make this refer to another, completely unrelated object, like: `var test = {}; obj.class1.call(test);`, then `test.property2` would be `ab`. `this` depends only on calling context in javascript, not on anything else.
Mewp
Yep, that solves the problem. I just have to explicitly define the calling context. Thank you!
Khoi
A: 

If you call it like so:

object1.class1();

Then this will refer to object1.

Motti