Home > Web Front-end > JS Tutorial > body text

Two ways to create classes using functions in Javascript

高洛峰
Release: 2016-12-06 13:58:24
Original
1455 people have browsed it

1. Use the function class

//myFunction.js
var CMyFunc=function()
{
//类的公共方法,供外部调用
this.Func1=function()
{
var i=0;
return i;
}
 
this.Func2=function()
{
_privateFunc();
}
 
//类中的私有方法,供公共方法调用
function _privateFunc()
{
return 0;
]
}
 
CMyFunc myFunc=new CMyFunc();
Copy after login

Usage: After introducing myFunction.js into other javascript files, directly use myFunc (global variable).Func1

2. Use the function class (2)

//myFunction.js
var CMyFunc=function()
{
var myFunc=new Object();
//类的公共方法,供外部调用
myFunc.Func1=function()
{
var i=0;
return i;
}
 
myFunc.Func2=function()
{
_privateFunc();
}
 
//类中的私有方法,供公共方法调用
function _privateFunc()
{
return 0;
]
 
return myFunc;
}
Copy after login

Usage: After introducing myFunction.js into other javascript files, initialize an object through var myFunc=new CMyFunc(). Advantages: 1. There are smart prompts when using the myFunc object function 2. There is no need to create global variables in myFunction.js 3. The this parameter in the myFunc object function points to the same point

3. Use jquery extension

//myFunction.js
(function ($) {
$.MyFunc={};
 
$.MyFunc.Func1=function()
{
var i=0;
return i;
}
 
$.MyFunc.Func2=function()
{
var i=0;
return i;
}
 
 
})(jQuery);
Copy after login

Usage: After introducing myFunction.js into other javascript files, just use $.MyFunc.Func1() directly

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