JavaScript定义类和对象的方法_javascript技巧

WBOY
Release: 2016-05-16 16:30:04
Original
1404 people have browsed it

本文实例讲述了JavaScript定义类和对象的方法。分享给大家供大家参考。具体方法如下:

在JS中,类和对象有多种不同的写法,因为本人对JS也不怎么熟,所以就本人的理解来写,如果哪位朋友发现有不对,请告之,共同学习.
JS定义一个类有两种定法(我只知道这两种):

1. 定义函数的方式:
定义:

复制代码代码如下:
function classA(a)
{
this.aaa=a; //添加一个属性
this.methodA=function(ppp) //添加一个方法
{
alert(ppp);
}
}
classA.prototype.color = "red"; //用prototype方法添加对象的属性,此方法也适用于类的实例(对象)
classA.prototype.tellColor = function() //用prototype方法添加对象的方法,此方法也适用于类的实例(对象)
{
return "color of "+this.name+" is "+this.color;
}

使用方法:
复制代码代码如下:
var oClassA=new classA('This is a class example!'); //实例化类
var temp=oClassA.aaa; //使用属性aaa
oClassA.methodA(temp); //使用方法methodA


2. 先实例化Object类的方式
定义:
复制代码代码如下:
var oClassA=new Object(); //先实例化基础类Object
oClassA.aaa='This is a class example!'; //添加一个属性
oClassA.methodA=function(ppp) //添加一个方法
{
alert(ppp);
}
oclassA.prototype.color = "red"; //用prototype方法添加对象的属性
oclassA.prototype.tellColor = function() //用prototype方法添加对象的方法
{
return "color of "+this.name+" is "+this.color;
}


使用方法:
可以直接拿oClassA来用,如:
复制代码代码如下:
var temp=oClassA.aaa; //使用属性aaa
oClassA.methodA(temp); //使用方法methodA

希望本文所述对大家的javascript程序设计有所帮助。

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
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!