Home >Web Front-end >JS Tutorial >The difference between two implementations of defining prototype methods in JS classes_javascript skills
We know that adding prototype methods to JavaScript classes is very simple. And the following two methods are commonly used, but are there any differences in the use of these two methods?
JScript Class:
function JSClass()
{
}
Extends prototype method:
JSClass.prototype.MethodA = function()
{
};
Or
function = JSClass.prototype.MethodA()
{
};
In fact, the definition of these two prototypes can be simplified and discussed. First, they are regarded as two functions, as follows:
Foo1();
function Foo1()
{
alert(This is Foo1.);
}
and Foo2();
var Foo2 = function()
{
alert(This is Foo2.);
}
There will obviously be no errors when running the first one, but there will be problems when running the second one. At this time, the system will say: Microsoft JScript runtime error: Object expected. This means that the function definition (Foo1) has the highest initialization priority in the script parser, which is easy to understand. If the function is not processed first, there will be no way to handle the function calls in the function. If we first define fn1() and then define fn2(), but call fn2 from fn1, then the parsing will not pass. Why Foo2 cannot be initialized? The definition of Foo2 is not a function definition at all. It is a standard assignment statement. The reason why Foo2(Foo2()) can be used like a standard function is entirely because it points to an instance of a function object. That’s all.
Let’s look at the two ways to import the prototype method. It’s very simple. And different execution priorities also determine the differences in their use. See the following example:
Execution:
var nc = new NormalClass();
nc.Method1();
nc.Method2();
<script>
<br>function NormalClass()
<br>{
<br> this.m_Property1 = ’P1 in Normal Class.’;
<br> this.m_Property2 = ’P2 in Normal Class.’;
<br><br> this.toString = function()
<br> {
<br> return ’[class NormalClass]’;
<br> }
<br><br> return new InnerClass();
<br><br> function InnerClass()
<br> {
<br> this.m_Property1 = ’P1 in Inner Class.’;
<br> this.m_Property2 = ’P2 in Inner Class.’;
<br><br> this.toString = function()
<br> {
<br> return ’[class InnerClass]’;
<br> }
<br> }
<br><br> InnerClass.prototype.Method1 = function()
<br> {
<br> alert(this.m_Property1);
<br> };
<br><br> function InnerClass.prototype.Method2()
<br> {
<br> alert(this.m_Property2);
<br> };
<br>}
<br></script> What is the effect? Why?