Michael Haufe (TNO) wrote:
> Jonas Thörnvall wrote:
>> var People = [
>> {Name: "Name", Surname: "Surname"},
>> {Name:"AAA", Surname:"ZZZ"},
>> {Name: "Name", Surname: "AAA"}
>> ];
>> I guess people is an array holding three indexes above?
>> The properties of people is Name and Surname
>
> JavaScript developers have a tendency to "golf" [1] their code just like
> Perl programmers. Which can make things unnecessarily terse.
But often also less error-prone. YMMV.
> I would have wrote the example like this:
>
> </script>
> class Person {
> constructor(name, surName) {
>
this.name = name;
> this.surName = surName
> }
> }
>
> var people = [
> new Person(Brendan", "Eich"),
> new Person("Alan","Kay"),
> new Person("Robert", "Carlyle")
> ]
Names starting with a capital letter should be reserved for constructors,
classes and constants That is, “People”, “Name”, and “Surname” should all
be lowercase here.
Using the same pattern as you used for “tracks”, one can set up the data and
have the custom instances without repeating oneself (ES 2015+):
people = people.map((obj) => new Person(
obj.name, obj.surname));
or, more backwards-compatible (ES Ed. 5+):
people = people.map(function (obj) {
return new Person(
obj.name, obj.surname);
});
Or, most backwards-compatible (all):
for (var i = people.length; i--;)
{
var obj = people[i];
people[i] = new Person(
obj.name, obj.surname);
};
If the class/type has a default constructor (and this is one example that
show that it is a good idea to have one), and provides means to set
individual properties, then this can be even simpler. For example:
people = people.map((obj) => {
var person = new Person();
Object.assign(person, obj);
});
It is also a good idea to have a constructor that in addition to positional
arguments accepts an initializer object as first and only argument.
people = people.map((obj) => new Person(obj));
Such a constructor is particularly useful with JSON.parse(json, reviver),
and in general it is a good idea if a constructor can be called as a
function for type conversion (like type casting). But apparently this is
not possible with ECMAScript classes:
class Person
{
constructor (...args)
{
if (!(this instanceof Person)) return new Person(...args);
/* initialize */
}
}
/* TypeError: Class constructor Person cannot be invoked without 'new' */
Person()
This works:
function Person (...args)
{
/*
* For backwards compatibility JSX:object.js introduces
* Function.prototype.construct(), and I am also thinking about
* adding Function.prototype.toFactory() for DRY.
*/
if (!(this instanceof Person)) return new Person(...args);
/* initialize */
}
/* > Person {} */
Person()
BTW, one should have read <
http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/>.
--
PointedEars
FAQ: <
http://PointedEars.de/faq> | <
http://PointedEars.de/es-matrix>
<
https://github.com/PointedEars> | <
http://PointedEars.de/wsvn/>
Twitter: @PointedEars2 | Please do not cc me./Bitte keine Kopien per E-Mail.