Home >Web Front-end >JS Tutorial >Two ways to create classes using functions in Javascript

Two ways to create classes using functions in Javascript

高洛峰
高洛峰Original
2016-12-06 13:58:241484browse

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();

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;
}

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);

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

Statement:
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