Home > Web Front-end > JS Tutorial > JavaScript object-oriented methods and differences_js object-oriented

JavaScript object-oriented methods and differences_js object-oriented

WBOY
Release: 2016-05-16 19:05:32
Original
744 people have browsed it

The first one: use this keyword

function Class1()
{
this.onclick = function(e)
{
for (var i=0; i                                                                                                                 Add properties and methods, similar to most OOP languages, and can even be added at runtime.

Second: Use prototype keyword

function clickFunc(e)
{
for (var i=0; i {
var a = new Date();
}
}

function Class2()
{
}

Class2.prototype.onclick = clickFunc;

This usage is not as flexible as the first one. However, before an object new comes out, 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 method because the first method is relatively concentrated and easier to read the code. But when running, their running efficiency is quite different. Let’s take a look at the test code below:

var total = new Array();

function Test1()
{
var a = new Date();
for (var i=0; i {
var c = new Class1();
//total.push(c);
}
var b = new Date();
alert(b.getTime()-a.getTime());
}
function Test2()
{
var a = new Date ();
for (var i=0; i {
var c = new Class2();
//total.push(c);
}
var b = new Date();
alert(b.getTime()-a.getTime());
}
The first step is to test the execution time: find Test1 () takes 142ms, while Test2() only takes 50ms. In terms of time efficiency, the prototype method is more efficient than this.

The second step is to test the memory usage. Remove the comments from the line total.push(c);. The reason why we need to add them to the array is to prevent there are many objects when creating them. , objects that are not referenced are GCed. It turns out that the gap is not that big. The first method takes up 20 to 30 M of memory, while the second method only requires more than 100 K.

Cause inference:
When processing these two codes, the first one, the JS parser, creates a separate method for each object, which increases the memory overhead and creates method, the running time is increased. Second, the JS parser, like most OOP compilers, stores the object's data segment and method segment separately. For the object's private data, there is one copy for each object, and these methods are Put it in the public method section, so it can reduce running time and memory overhead.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template