Domanda

In the source code for a reusable d3 library (code found here: https://github.com/bugzu/reD3/blob/master/src/area.js ) nearly every line contains a reference to this. Website homepage: http://bugzu.github.io/reD3/#/

Example:

(function(global) {

    global.reD3 = global.reD3 || {};

    function Area(element, options) {
        this.element = element;
        this.options = options;
        this.init();
    }

    Area.prototype = {

        init: function() {
            var options = this.options,
            width = options.width || 960,
            height = options.height || 500,
            oMargin = options.margin;

            var margin = {
                top: 20,
                right: 30,
                bottom: 30,
                left: 40
            },

            margin = reD3.util.mixin(margin, oMargin);

            width = this.width = width - margin.left - margin.right;
            height = this.height = height - margin.top - margin.bottom;
            var xValue = this.xValue = options.xValue || 'date';
            var yValue = this.yValue = options.yValue || 'value';

What is the purpose of this being used so frequently? What are the advantages/disadv of a technique like this for reusable (chart) components?

È stato utile?

Soluzione

Since Area is a class (you can tell by the use of 'this' in the constructor function, and calls to it will use the new keyword), the use of this modifies the object rather than a local or global variable. Regardless of whether a library is for charts or anything else, using this encourages encapsulation, although it's admittedly much less obvious than in other languages with classes.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top