Using javascript 'this'

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' mean? object1 or class1? And whenever I want to define a class constructor inside an object, what is the best way to do this?

+3
source share
2 answers

For class1, because you cannot create an object of type object1.

However, if the code looks like this:

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

You may have:

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

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

So this may be context specific.

+2
source

If you call it like this:

object1.class1();

Then thiswill refer to object1.

+1
source

Source: https://habr.com/ru/post/1760482/


All Articles