Neither I can’t put in my head What is the designer in JavaScript?
Why do we change it and use it?
For example:
var duck = function (name) {
this.name = Name;
};
Duck.prototype.Quack = Function () {
Return this.name + "Duck: Quack-Quack!";
};
Var TalkingDuck = Function (Name) {
Duck.call (this, name);
}
TalkingDuck.Prototype = object.create (duck.prototype);
TalkingDuck.prototype.constructor = TalkingDuck;
How effectively can we use it in practice?
Explain it short and understandable, or by turnover 🙂
Answer 1, Authority 100%
In practice Constructor
is usually not used.
what it is:
-
any function
f ()
has thef.prototype
property, which is the object with theconstructor
property equal to the function itself. That is:f.prototype.constructor === f
This means that any object
o
designed by thef
function, which has not replaced theprototype
, will be performedo.constructor / * === (new f ()). Constructor * / === F
-
In addition,
Constructor
is defined in embedded objects (Number
,Boolean
,String
,Regexp
, …) and, due to “boxing”, even at primitive values ​​(1
,"ASDF"
,/ Reg [ EE] XP /
). In the latter it does not make sense to change, because The change concerns the temporarily created shell object over the primitive, and does not actually have effect.
Some trying to use this property to use this.constructor
in the object method to determine the function with which you can build the same object (Example ).
However, if you replace Prototype
, as in your example:
talkingduck.prototype = object.create (duck.prototype);
.. then talkingduck.prototype.constructor
already equal to duck
, which means that new TalkingDuck ()
will not have the expected Constructor
(=== Duck
, not TalkingDuck
). It is treated with an additional finge:
talkingduck.prototype.constructor = TalkingDuck;
… But to rely on the fact that Constructor
“is correct” installed for all objects, you need this phint for each of them.
Well, then decide for yourself – you need this Constructor
or not.
ANSWER 2, AUTHORITY 11%
If in a nutshell Constructor Returns a reference to a function that created the prototype of the instance.
In fact, Constructor allows you to dynamically manage the creation of an object. Thereby ensures great flexibility. However, this does not work for primitive values ​​(such as True, 1, “Text”).
Answer 3
Supplement: The designer property is not listed.
object.getownPropertyDescriptor (duck.prototype, 'Constructor')
Here An example .
Answer 4
Write the code in TypeScript and see how he passed it to JavaScript. Everything will become clear!
Link .
Under the standard OOP, I mean OOP, which is used in C++ / Java / C # … JavaScript uses prototype programming – the style of object-oriented programming, in which there is no concept of class, and the inheritance is carried out by cloning an existing instance of the object – prototype.