Article Introduction: when using dynamic prototyping mode, you cannot use object literals to override prototypes. As explained earlier, if you rewrite the prototype if you have already created an instance, you will sever the connection between the existing instance and the new prototype. |
Developers with other OO language experiences are likely to be very confused when they see independent constructors and prototypes. The dynamic prototyping model is a solution to this problem, encapsulating all the information in the constructor, and maintaining the advantage of using constructors and prototypes in the constructor by initializing the prototype (only where necessary). In other words, you can determine whether you need to initialize a prototype by checking whether a method that should exist is valid. Take a look at an example:
function person (name, age, Job) {
//attribute
this.name = name;
This.age = age;
This.job = job;
Method
if (typeof this.sayname!= "function") {
Person.prototype.sayName = function () {
alert (this.name); c11/>};
}
var person = new Person ("Nicholas", "Software Engineer");
Person.sayname (); "Nicholas"
This is only added to the prototype if the Sayname () method does not exist. This code is only executed when the constructor is first invoked. Since then, the prototype has been initialized and no further modifications are required. Keep in mind, however, that the modifications made here to the prototype are immediately reflected in all instances. Therefore, this method can indeed be said to be very perfect. Where an If statement can check for any properties or methods that should exist after initialization-without having to check each property and method with a bunch of if statements, just check one of them. For objects created in this pattern, you can also use the instanceof operator to determine its type.
When using dynamic prototyping mode, you cannot use object literals to override prototypes. As explained earlier, if you rewrite the prototype if you have already created an instance, you will sever the connection between the existing instance and the new prototype.