Using 'this' inside nested Prototype subtypes

I have a class and gave the prototype some sub-objects to make the namespace easier. These sub-objects have methods. I cannot figure out how to use this

inside these methods to access properties set using the constructor.

I have a feeling bind

, call

and are apply

somehow related, but I'm having trouble understanding what they are doing and how the whole OOP job works in general. There are many resources, but they are all either too low level or very high level, I do not understand them. Thank!

function Object(
    argument1,
    argument2
){
    this.property1  = argument1;
    this.property2  = argument2;
}

Object.prototype    = {
    subObject1  : {
        method1 : function(){
            return this.property1;
        }
    },
    subObject2  : {
        method1 : function(){
            return this.property2;
        }
    }
}

var foo = new Object(11, 22);
var bar = new Object(33, 44);

console.log(foo.subObject1.method1()); //I'd like this to return 11
console.log(foo.subObject2.method1()); //I'd like this to return 22

console.log(bar.subObject1.method1()); //I'd like this to return 33
console.log(bar.subObject2.method1()); //I'd like this to return 44

      

+2


source to share


1 answer


Whenever you call a form foo.bar()

, the this

internally bar

will refer to foo

. If not , you bind a function to a specific value using .bind

or use the new "arrow" functions in ES6.

Thus, one solution might be to bind methods to a specific instance. However, the instance doesn't exist until you call the constructor function. This means that you must create, subObjectX

inside the constructor:

function MyObject(argument1, argument2) {
    this.property1  = argument1;
    this.property2  = argument2;

    this.subObject1 = {
        method1: function(){
             return this.property1;
        }.bind(this)
    };

    this.subObject2 = {
        method1: function(){
            return this.property2;
        }.bind(this)
    };
}

      

Or using the new ES6 arrow functions; they take this

from the context in which they are created (as opposed to regular functions):

// ES6 only!
function MyObject(argument1, argument2) {
    this.property1  = argument1;
    this.property2  = argument2;

    this.subObject1 = {
        method1: () => {
             return this.property1;
        }
    };

    this.subObject2 = {
        method1: () => {
            return this.property2;
        }
    };
}

      



This means that each instance has its own copy of the sub-object.

If you want to define methods on a prototype, you always need to pass the receiver via .call

or .apply

:

foo.subObject1.method1.call(foo);

      

in this case, there is no benefit to assigning it to a prototype at all, and you can just have a simple function that takes an object ( method1(foo)

).

+4


source







All Articles