Khoi
Khoi

Reputation: 4635

javascript 'this' usage

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?

Upvotes: 3

Views: 367

Answers (2)

Motti
Motti

Reputation: 114695

If you call it like so:

object1.class1();

Then this will refer to object1.

Upvotes: 1

Mewp
Mewp

Reputation: 4715

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.

Upvotes: 2

Related Questions