Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically set arguments as instance properties in ES6

CoffeeScript automatically sets the arguments as instance properties in the constructor if you prefix the arguments with @.

Is there any trick to accomplish the same in ES6?

like image 968
William Lepinski Avatar asked Dec 17 '14 15:12

William Lepinski


3 Answers

Felix Kling's comment outlines the closest you'll get to a tidy solution for this. It uses two ES6 features—Object.assign and the object literal property value shorthand.

Here's an example with tree and pot as the instance properties:

class ChristmasTree {
    constructor(tree, pot, tinsel, topper) {
        Object.assign(this, { tree, pot });
        this.decorate(tinsel, topper);
    }

    decorate(tinsel, topper) {
        // Make it fabulous!
    }
}

Of course, this isn't really what you wanted; you still need to repeat the argument names, for one thing. I had a go at writing a helper method which might be a bit closer…

Object.autoAssign = function(fn, args) {

    // Match language expressions.
    const COMMENT  = /\/\/.*$|\/\*[\s\S]*?\*\//mg;
    const ARGUMENT = /([^\s,]+)/g;

    // Extract constructor arguments.
    const dfn     = fn.constructor.toString().replace(COMMENT, '');
    const argList = dfn.slice(dfn.indexOf('(') + 1, dfn.indexOf(')'));
    const names   = argList.match(ARGUMENT) || [];

    const toAssign = names.reduce((assigned, name, i) => {
        let val = args[i];

        // Rest arguments.
        if (name.indexOf('...') === 0) {
            name = name.slice(3);
            val  = Array.from(args).slice(i);
        }

        if (name.indexOf('_') === 0) { assigned[name.slice(1)] = val; }

        return assigned;
    }, {});

    if (Object.keys(toAssign).length > 0) { Object.assign(fn, toAssign); }
};

This auto-assigns any parameters whose names are prefixed with an underscore to instance properties:

constructor(_tree, _pot, tinsel, topper) {
    // Equivalent to: Object.assign({ tree: _tree, pot: _pot });
    Object.autoAssign(this, arguments);
    // ...
}

It supports rest parameters, but I omitted support for default parameters. Their versatility, coupled with JS' anaemic regular expressions, makes it hard to support more than a small subset of them.

Personally, I wouldn't do this. If there were a native way to reflect on the formal arguments of a function, this would be really easy. As it is, it's a mess, and doesn't strike me as a significant improvement over Object.assign.

like image 106
Jordan Gray Avatar answered Oct 13 '22 21:10

Jordan Gray


Legacy support script

I've extended Function prototype to give access to parameter auto-adoption to all constructors. I know we should be avoiding adding functionality to global objects but if you know what you're doing it can be ok.

So here's the adoptArguments function:

var comments = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/g;
var parser = /^function[^\(]*\(([^)]*)\)/i;
var splitter = /\s*,\s*/i;

Function.prototype.adoptArguments = function(context, values) {
    /// <summary>Injects calling constructor function parameters as constructed object instance members with the same name.</summary>
    /// <param name="context" type="Object" optional="false">The context object (this) in which the the calling function is running.</param>
    /// <param name="values" type="Array" optional="false">Argument values that will be assigned to injected members (usually just provide "arguments" array like object).</param>

    "use strict";

    // only execute this function if caller is used as a constructor
    if (!(context instanceof this))
    {
        return;
    }

    var args;

    // parse parameters
    args = this.toString()
        .replace(comments, "") // remove comments
        .match(parser)[1].trim(); // get comma separated string

    // empty string => no arguments to inject
    if (!args) return;

    // get individual argument names
    args = args.split(splitter);

    // adopt prefixed ones as object instance members
    for(var i = 0, len = args.length; i < len; ++i)
    {
        context[args[i]] = values[i];
    }
};

The resulting call that adopts all constructor call arguments is now as follows:

function Person(firstName, lastName, address) {
    // doesn't get simpler than this
    Person.adoptArguments(this, arguments);
}

var p1 = new Person("John", "Doe");
p1.firstName; // "John"
p1.lastName; // "Doe"
p1.address; // undefined

var p2 = new Person("Jane", "Doe", "Nowhere");
p2.firstName; // "Jane"
p2.lastName; // "Doe"
p2.address; // "Nowhere"

Adopting only specific arguments

My upper solution adopts all function arguments as instantiated object members. But as you're referring to CoffeeScript you're trying to adopt just selected arguments and not all. In Javascript identifiers starting with @ are illegal by specification. But you can prefix them with something else like $ or _ which may be feasible in your case. So now all you have to do is detect this specific naming convention and only add those arguments that pass this check:

var comments = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/g;
var parser = /^function[^\(]*\(([^)]*)\)/i;
var splitter = /\s*,\s*/i;

Function.prototype.adoptArguments = function(context, values) {
    /// <summary>Injects calling constructor function parameters as constructed object instance members with the same name.</summary>
    /// <param name="context" type="Object" optional="false">The context object (this) in which the the calling function is running.</param>
    /// <param name="values" type="Array" optional="false">Argument values that will be assigned to injected members (usually just provide "arguments" array like object).</param>

    "use strict";

    // only execute this function if caller is used as a constructor
    if (!(context instanceof this))
    {
        return;
    }

    var args;

    // parse parameters
    args = this.toString()
        .replace(comments, "") // remove comments
        .match(parser)[1].trim(); // get comma separated string

    // empty string => no arguments to inject
    if (!args) return;

    // get individual argument names
    args = args.split(splitter);

    // adopt prefixed ones as object instance members
    for(var i = 0, len = args.length; i < len; ++i)
    {
        if (args[i].charAt(0) === "$")
        {
            context[args[i].substr(1)] = values[i];
        }
    }
};

Done. Works in strict mode as well. Now you can define prefixed constructor parameters and access them as your instantiated object members.

Extended version for AngularJS scenario

Actually I've written an even more powerful version with following signature that implies its additional powers and is suited for my scenario in my AngularJS application where I create controller/service/etc. constructors and add additional prototype functions to it. As parameters in constructors are injected by AngularJS and I need to access these values in all controller functions I can simply access them, via this.injections.xxx. Using this function makes it much simpler than writing several additional lines as there may be many many injections. Not to even mention changes to injections. I only have to adjust constructor parameters and I immediately get them propagated inside this.injections.

Anyway. Promised signature (implementation excluded).

Function.prototype.injectArguments = function injectArguments(context, values, exclude, nestUnder, stripPrefix) {
    /// <summary>Injects calling constructor function parameters into constructed object instance as members with same name.</summary>
    /// <param name="context" type="Object" optional="false">The context object (this) in which the calling constructor is running.</param>
    /// <param name="values" type="Array" optional="false">Argument values that will be assigned to injected members (usually just provide "arguments" array like object).</param>
    /// <param name="exclude" type="String" optional="true">Comma separated list of parameter names to exclude from injection.</param>
    /// <param name="nestUnder" type="String" optional="true">Define whether injected parameters should be nested under a specific member (gets replaced if exists).</param>
    /// <param name="stripPrefix" type="Bool" optional="true">Set to true to strip "$" and "_" parameter name prefix when injecting members.</param>
    /// <field type="Object" name="defaults" static="true">Defines injectArguments defaults for optional parameters. These defaults can be overridden.</field>
{
    ...
}

Function.prototype.injectArguments.defaults = {
    /// <field type="String" name="exclude">Comma separated list of parameter names that should be excluded from injection (default "scope, $scope").</field>
    exclude: "scope, $scope",
    /// <field type="String" name="nestUnder">Member name that will be created and all injections will be nested within (default "injections").</field>
    nestUnder: "injections",
    /// <field type="Bool" name="stripPrefix">Defines whether parameter names prefixed with "$" or "_" should be stripped of this prefix (default <c>true</c>).</field>
    stripPrefix: true
};

I exclude $scope parameter injection as it should be data only without behaviour compared to services/providers etc. In my controllers I always assign $scope to this.model member even though I wouldn't even have to as $scope is automatically accessible in view.

like image 43
Robert Koritnik Avatar answered Oct 13 '22 19:10

Robert Koritnik


For those who stumble upon this looking for Angular 1.x solution

Here's how it could work:

class Foo {
  constructor(injectOn, bar) {
    injectOn(this);
    console.log(this.bar === bar); // true
  }
}

And here's what injectOn service does under the hood:

.service('injectOn', ($injector) => {
  return (thisArg) => {
    if(!thisArg.constructor) {
      throw new Error('Constructor method not found.');
    }
   $injector.annotate(thisArg.constructor).map(name => {
      if(name !== 'injectOn' && name !== '$scope') {
        thisArg[name] = $injector.get(name);
      }
    });
  };
});

Fiddle link


Edit: Because $scope is not a service, we cannot use $injector to retrieve it. To my knowledge, it's not possible to retrieve it without re-instantiating a class. Hence why, if you inject it and need it outside constructor method, you'll need to assign it to this of your class manually.

like image 23
Maciej Gurban Avatar answered Oct 13 '22 20:10

Maciej Gurban