惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
Jina AI
Jina AI
罗磊的独立博客
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
J
Java Code Geeks
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
InfoQ
月光博客
月光博客
博客园_首页
Vercel News
Vercel News
P
Proofpoint News Feed
GbyAI
GbyAI
Y
Y Combinator Blog

博客园 - 芸

Xtragrid的图片显示 N×N矩阵螺旋打印输出 数组int[],int[,]的区别 转载 使用ActiveReport for .net 进行报表开发 oracle数据库之间的数据拷贝 VS2003 水晶报表服务器端部署 SQL操作全集 合并多行的字符串—oarcle(转) 在网页上使用户按Enter键自动跳到下一控件,并禁止使用鼠标右键和其他快捷键的HTC控件 字符串样式的格式化 oracle 存储过程的基本语法 2007年终总结 主从表XtarGrid设计 dotNet常用快捷键 最美的十大经典爱情句子 自定义控件脚本校验 在DataGrid中使用单选框 ActiveReport子报表 正则表达式收藏
JavaScript面向对象
· 2007-02-25 · via 博客园 - 芸
 

           JavaScript面向对象

面向对象的编程思想三大要素:

l       封装

l       继承

l       多态

JavaScript如何实现OOP

l       封装(Wrap)
JavaScript的对象封装,主要依靠function来实现。以下是一个简单的示例:

//*********************************************

// 定义Pet(宠物)对象

//*********************************************

function Pet() {

        //名称

        this.name = null;

        //颜色

        this.color = null;

        //获取名称

        this.getName = function() {

                return this.name;

        };

        //设置名称

        this.setName = function(newName) {

                this.name = newName;

        };

        //获取颜色

        this.getColor = function() {

                return this.color;

        };

        //设置颜色

        this.setColor = function(newColor) {

                this.color = newColor;

        };

        //定义一个需要实现的方法
        this.getFood = null;

        //获取宠物的描述信息

        this.toString = function() {

            return "The pet is " + this.name +",it's "

+this.color+",and it likes "+this.getFood()+".";
        };

}

l       继承(inheritance)
JavaScript的继承的实现主要依靠prototype(原型)来实现,下面为Pet类编写一个子类。

//*********************************************

// 定义Cat(猫)对象

//*********************************************

function Cat() {

        //实现Pet中定义的getFood方法

        this.getFood = function() {

                return "fish";

        };

}

//声明Cat的原型,即Cat的父类

Cat.prototype = new Pet;

多层次继承

//*********************************************

// 定义PersianCat(波斯猫)对象

//*********************************************

function PersianCat() {

}

//声明PersianCat的原型,即PersianCat的父类

PersianCat.prototype = new Cat;

l       重载(override)与多态(Polymorphism)

//重载Pet的toString方法

PersianCat.prototype.toString = function() {

        return "It's just a persian cat.";

};