Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript method execution order

While reading yeoman generator documentation (http://yeoman.io/generators.html#writing-your-first-generator), I came across following line.

Starting from the top, every method you place on the BlogGenerator.prototype will be invoked in the order you've written them.

How does yeoman execute methods in the same order?

like image 526
apostopher Avatar asked Mar 26 '26 18:03

apostopher


1 Answers

Actually, it's as easy as...

var methods = Object.keys(Object.getPrototypeOf(this));

Here's the Github link. And yes, they're invoked, not evaluated:

/*
 * Runs the generator, executing top-level methods in the order they
 * were defined.
 */
// ...
async.series(methods.map(resolve), runHooks); 

Technically that might end up in a trouble if one defines a property with a numeric name. For example:

var Foo = function() {};
Foo.prototype.bar  = function() { console.log('I am bar'); };
Foo.prototype[123] = function() { console.log('I am 123'); };

var foo = new Foo(); 
var methods = Object.keys(Object.getPrototypeOf(foo)); // ['123', 'bar']
methods.map(function(fn) { foo[fn]() }); 
// I am 123
// I am bar

But I assume those cases are considered non-existant. For all the others, it looks like V8 is honoring the properties' insertion order - otherwise the code given won't function as expected, obviously.

like image 184
raina77ow Avatar answered Mar 28 '26 09:03

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!