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

Javascript 类与静态类的实现_js面向对象

WBOY
Release: 2016-05-16 18:30:48
Original
934 people have browsed it

今天所要说的就是,如何在Javascript里写类与静态类,这是本人一惯用的方法,你也可以有更为方便的,也可以发发评论跟大家交流交流。
首先说说类,在一个类里我们会有以下的几个特征:
1. 公有方法
2. 私有方法
3. 属性
4. 私有变量
5. 析构函数
我们直接看一个例子:
类例子

复制代码 代码如下:

/***定义类***/
var Class = function(){
var _self = this;//把本身引用负值到一变量上
var _Field = "Test Field"; //私有字段
var privateMethod = function(){ //私有方法
alert(_self.Property); //调用属性
}
this.Property = "Test Property"; //公有属性
this.Method = function(){ //公有方法
alert(_Field); //调用私用字段
privateMethod(); //调用私用方法
}
}

这里我已把注释都写上,大家大概也会一眼就看得明白。对于少写JS的朋友,可能会觉得奇怪为什么我会定义一个_self的变量, 因为在js里,this不用对于其他的对象语言,他的解析过程与运行过程中this会改变的。这里简单说说js里this的定义,若有需要我可以开多一篇。
定义:this是包含它的函数作为方法被调用时所属的对象。
特征:this的环境可以随着函数被赋值给不同的对象而改变!
有兴趣的朋友可以网上找找资料了解一下,说回正题,这里的_self目的是为了开多一个私有的变量,直接指向类的本身。
刚刚还说到一个析构函数的问题,这可以直接用代码来实现。在函数的最后直接写执行代码就OK。
代码
复制代码 代码如下:

/***定义类***/
var Class = function(){
var _self = this;//把本身引用负值到一变量上
var _Field = "Test Field"; //私有字段
var privateMethod = function(){ //私有方法
alert(_self.Property); //调用属性
}
this.Property = "Test Property"; //公有属性
this.Method = function(){ //公有方法
alert(_Field); //调用私用字段
privateMethod(); //调用私用方法
}
/***析构函数***/
var init = function(){
privateMethod();
}
init();
}

使用这个类,引用我同事的那句“简单得很!”
var c = new Class();
这样就OK
类的定义就说完了,静态类,要等到下一次了。因为有MM叫我去喝茶
一个人能够走多远,取决于与谁同行
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!