简体   繁体   中英

Modifying “this” variables

I was playing around with modifying Array Prototype, but I'm stumped at this part. Would be great if you could help me.

Alright, suppose I want to add a function "Parent" to Array.prototype

Array.prototype.Parent = function() { 
    console.log(this);
}

Next, I want to add a Child function to the Parent function. I would do it like this:

Array.prototype.Parent.Child = function() { 
    console.log(this);
}

Now, I want both this in Parent and Child to refer to the array itself. So:

[1,2,3].Parent(); // Would output [1,2,3];
[1,2,3].Parent.Child(); // Want it to print [1,2,3];

Basically, I want this variable in child to refer to the array instead of the Parent Function. Any insight?

You can make Parent a getter that returns a unique function for each array, providing context:

Object.defineProperty(Array.prototype, 'parent', {
    configurable: true,
    get: function () {
        var that = this;

        function parent() {
            console.log(that);
        }

        parent.child = function () {
            console.log(that);
        };

        return parent;
    },
});

The problem here is how the this variable is identified if you have a series of object lookups then a function call. Like this.

foo.bar.baz.qux();

The qux method has a this value equal to foo.bar.baz . So in essence functions in javascript have a hidden argument this that is the object they are called on.

There is no way to modify this behavior in javascript.

You can reassign this using Function.bind .

var myArray = [1,2,3];

myArray.Parent.Child.bind( myArray )();

In my example, myArray.Parent.Child is the Function you defined in your example - then we use bind to create a copy of the function with this set to myArray , then we use the () operator to invoke it.

This can be reduced to a single line with a self-executing lambda (ES6):

( x => x.Parent.Child.bind( x )() )( myArray );

...which is equivalent to this in ES5:

( function( x ){ return x.Parent.Child.bind( x )() } )( myArray );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM