As a dynamic language, object JS in javascript has considerable degrees of freedom in syntax, so it creates a function and N writing styles.
In JS, there are generally two ways to implement OOP:
The first: Use this keyword
functionClass1()
{
this.onclick=function(e)
{
for(vari=0;i<1000;i++)
{
vara=newDate();
}
}
}
Using this. method can add properties and methods to objects flexibly, and it is similar to most OOP languages, and can even be added during operation.
The second type: use prototype keywords
functionclickFunc(e)
{
for(vari=0;i<1000;i++)
{
vara=newDate();
}
}
functionClass2()
{
}
Class2.prototype.onclick=clickFunc;
In terms of usage, there is no first one that seems flexible. However, before an object is new, you can also add the properties and methods of an object at any time.
But they are not equal. Relatively speaking, I prefer the first one because the first method is relatively concentrated and easier to read the code. However, when running, their operating efficiency varies greatly. Let's take a look at the test code below:
vartotal=newArray();
functionTest1()
{
vara=newDate();
for(vari=0;i<10000;i++)
{
varc=newClass1();
//total.push(c);
}
varb=newDate();
alert(b.getTime()-a.getTime());
}
functionTest2()
{
vara=newDate();
for(vari=0;i<10000;i++)
{
varc=newClass2();
//total.push(c);
}
varb=newDate();
alert(b.getTime()-a.getTime());
}
The first step is to test the execution time: it is found that Test1() takes 142ms, while Test2() only takes 50ms. In terms of time efficiency, the prototype method is more efficient than this.