Home > Web Front-end > JS Tutorial > 5 ways to write JS object-oriented_js object-oriented

5 ways to write JS object-oriented_js object-oriented

WBOY
Release: 2016-05-16 18:48:50
Original
987 people have browsed it

Java code

Copy code The code is as follows:

//First way of writing
function Circle(r) {
this.r = r;
}
Circle.PI = 3.14159;
Circle.prototype.area = function() {
return Circle.PI * this. r * this.r;
}
var c = new Circle(1.0);
alert(c.area());

Java code
Copy code The code is as follows:

//The second way of writing
var Circle = function() {
var obj = new Object();
obj.PI = 3.14159;
obj.area = function( r ) {
return this.PI * r * r;
}
return obj;
}
var c = new Circle();
alert( c.area( 1.0 ) );

Java code
Copy code The code is as follows:

//The third way of writing
var Circle = new Object();
Circle.PI = 3.14159;
Circle.Area = function( r ) {
return this.PI * r * r;
}
alert( Circle.Area( 1.0 ) );

Java code
Copy code The code is as follows:

//No. 4 A way to write
var Circle={
"PI":3.14159,
"area":function(r){
return this.PI * r * r;
}
} ;
alert( Circle.area(1.0) );

Java code
Copy code The code is as follows:

//The fifth way to write
var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this .PI;}");
alert( (new Circle()).area(1.0) );

Let’s discuss these five writing methods, their advantages and disadvantages, and which one compares Norms, especially the last two, are often seen.
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