getButterfly
Resume

Giving Object Context to Function Calls

JavaScript has a dynamic object named this. By default, this equals to the global object container, so if we have a global variable named x, then this.x === x. The code below will display the value of x, which is 10.

var x = 10;
var print_x = function() {
    console.log(this.x);
};

print_x();

Accessing this.x in a method means accessing attribute x of the object containing this method. We can use this feature by assigning a JavaScript function to an object attribute. The code below will display a value of 20.

var print_x = function() {
    console.log(this.x);
};

var y = {
    'x': 20,
    print_x: print_x
};

y.print_x();

You can see that the value of this in the print_x() function has changed depending on where it was assigned from. The code below will display a value of 30.

var z = {'x': 30, print_x: print_x};

z.print_x ();

If desired, so that the value of this does not change whenever print_x() function is reassigned, other techniques are required.

See the bind() function below:

Function.prototype.bind = function() (
    var fn = this,
        args = Array.prototype.slice.call(arguments),
        object = args.shift();

    return function() (
        return fn.apply(object, args.concat (Array.prototype.slice.call(arguments)));
    );
);

Now the code below will still display the value of 20 despite what being called is z.print_x:

var y = {'x': 20};

print_x = print_x.bind(y);

var z = {
    'x': 30,
    print_x: print_x
};

z.print_x();

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.


Leave a Reply


My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.