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

推荐订阅源

Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
Y
Y Combinator Blog
D
DataBreaches.Net
IT之家
IT之家
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
H
Help Net Security
GbyAI
GbyAI
C
Check Point Blog
L
LangChain Blog
小众软件
小众软件
T
The Blog of Author Tim Ferriss
MyScale Blog
MyScale Blog
G
Google Developers Blog
月光博客
月光博客
V
V2EX
M
MIT News - Artificial intelligence
博客园 - 叶小钗

博客园 - 芸

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.";

};