B
B
Bogdan2018-03-11 17:14:13
JavaScript
Bogdan, 2018-03-11 17:14:13

Prototype constructor?

Hello.
1) Does it make sense to specify a prototype constructor for a child object, as I understand it, this is only a function reference, and if it is not necessary to use it?

proto = { color: green }
const Son = function( name ) { }
Son.prototype = Object.create( proto )
Son.prototype.constructor = Son //

2) What is the best way to add your properties to the prototype
Son.prototype = Object.create( proto, { constructor: { value: Son }, foo: { writable: false, configurable: false, value: 'привет' } } )

or
Son.prototype = Object.create( proto );
Son.prototype.constructor =  Son;
Son.prototype.foo = 'привет';

3) What is the best way to add your own methods, is this the only option, or is there a more elegant solution, for example, create an object with your own methods and glue it with a prototype?
Son.prototype.test= function() { return this };
Son.prototype.test1= function() { return this };
Son.prototype.test2= function() { return this };
Son.prototype.test3= function() { return this };
Son.prototype.test4= function() { return this };
Son.prototype.test5= function() { return this };

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2018-03-11
@bogdan_uman

Does it make sense to specify a prototype constructor for a child object, as I understand it, this is only a function reference, and if it is not necessary to use it?
Every constructor has a prototype. The default is Object.prototype.
If you need a prototype please let me know. If you don't need it, you don't need it either. It's obvious.
Only one amendment: a prototype is an object, which (like other objects) consists of fields, among which there are functions.
What is the best way to add custom properties to the prototype
I don't know. IMHO, for applied tasks it is better to do so that it is easier to read.
What is the best way to add your own methods, is it the only option, or is there a more elegant solution, for example, create an object with your own methods and glue it with a prototype?
It doesn't matter, but there's one thing to keep in mind.
Let's say we defined a Son constructor and gave it Son.prototype one way or another. For simplicity, let's assume that the prototype consists only of functions. Then we created several instances (new Son).
Next, suppose we want to add a new method to the prototype or modify an existing one.
Here it is necessary to decide whether (1) we will change the prototype of already created instances, or (2) we will leave the old prototype for the created instances, and the new one for the created ones.
PS Finally, new syntactic constructions have appeared in the latest editions. They shouldn't be forgotten either.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question