Home > Web Front-end > JS Tutorial > JavaScript creation object and construction class implementation code_js object-oriented

JavaScript creation object and construction class implementation code_js object-oriented

WBOY
Release: 2016-05-16 18:48:43
Original
981 people have browsed it

Create an object
Java code

Copy code The code is as follows:



Using json (javaScript Object Notation) to create objects has the same effect as above.
Java code
Copy code The code is as follows:

function sayLoudly(){
alert(this.firstName.toUpperCase());
}
var newObject={
firstName:"frank",
sayName:function(){alert(this.firstName);},
sayLoudly:sayLoudly
};
//You can also do this
var newObject={
firstName: "frank",
sayName:function(){alert(this.firstName) ;},
sayLoudly:sayLoudly,
lastName:{
lastName:"ziggy",
sayName:function(){alert(this.lastName);}
}
} ;
newObject.lastName.sayName();

This is ok
Java code
Copy code The code is as follows:

function sayLoudly(){
alert(this.name.toUpperCase());
}
function sayName(){
alert(this.name);
}
var newObject={
name:"frank",
sayName:sayName,
sayLoudly:sayLoudly,
lastName:{
name:"ziggy",
sayName:sayName
}
};
newObject.lastName.sayName();

Classes in JavaScript, as well as constructors method. . .
Java code
Copy code The code is as follows:

function newClass(){
alert("constructor");
this.firstName="frank";
this.sayName=function(){alert(this.firstName);}
// return this;
}
//var nc=newClass();
var nc=new newClass();
//nc.firstName="ziggy"; is ok
nc.sayName();

You can also construct a class like this
Java code
Copy code The code is as follows:

function newClass(){
this.firstName="frank";
}
newClass.prototype.sayName=function(){
alert(this.firstName);
}
var nc=new newClass();
nc.firstName="ziggy";
nc.sayName();
var nc2=new newClass();
nc2.sayName ();

Usually prototypes are used to add methods, so that no matter how many instances there are, there is only one sayName method in the memory.
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