A question about prototype writing
I now have an object O, and I need to add an init method to it as follows:
first:
O.prototype = {
init:function () {
}
}
second category:
O.prototype.init = function () {
}
is there any difference between the two ways of writing? And is there anything you need to pay attention to in the invocation?
can actually expand the method on the prototype of o, but if you have a lot of methods, for the sake of the maintainability, robustness and readability of the code, we still adopt the first method, at least the method that is commonly used by the general public. I hope it will help you
the first way to overwrite the original prototype
is equivalent to assigning a value to O.prototype, making it point to a new object. The second way to write
is to add attributes to the original O.prototype object;
you can use both, but when you use them, it's best to use only one of them. When used together, it is important to note that the first method invalidates the method previously defined on O.prototype.
is equivalent to the following
let o = {a:1};
o.a = 2; //
o = {a:3} //
first of all, if you can directly use the second way, a reasonable guess is that O
is a function, then using the first method will replace prototype
and cause the constructor
to be inconsistent with the original. You can add (or deliberately change the constructor or something that will not be discussed here)
the first will directly overwrite the original prototype, and the second is to add methods to the original prototype