getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

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.

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

Added by Ciprian on Friday, January 12, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy