您的位置:首页 > Web前端 > JavaScript

JavaScript中的面向对象程序设计

2015-08-14 14:55 477 查看
面向对象程序设计主要是有3个特点:封装继承多态,这篇文章简单介绍如何在JavaScript实现类,以及如何继承类。

类的实现

js中没用关键字class,但是提供了关键字new和this。我们可以先声明一个构造函数,然后通过new这个构造函数,便完成了一个类的封装。例子如下:

function Cat(name, color){
this.name = name;
this.color = color;
this.type = "猫科";
}

var cat1 = new Cat("花花", "白");
var cat2 = new Cat("宝宝", "黑")
console.log("cat1 name: %s, color: %s", cat1.name, cat1.color);
console.log("cat2 name: %s, color: %s", cat2.name, cat2.color);


上面这种方法有个弊端:type字段是是所有Cat实例的公共属性,实际上在内存只需要存一份即可。但是通过new出来的每个实例都会单独保存一份,这样就造成了内存的浪费。

我们可以通过指定构造函数的prototype值来完成这个功能:
Cat.prototype.type="猫科"
,这样所有Cat的实例将共享这个
type
字段。类的成员函数也可以通过这样来设置。

类的继承

使用apply

function Animal(){
this.kind = "动物";
}

function Cat(name, color){
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}

var cat1 = new Cat("花花", "白");
console.log("cat1 name: %s, color: %s kind: %s", cat1.name, cat1.color, cat1.kind);


使用prototype

function Animal(){
this.kind = "动物";
}

function Cat(name, color){
this.name = name;
this.color = color;
}

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

var cat1 = new Cat("花花", "白");
console.log("cat1 name: %s, color: %s kind: %s", cat1.name, cat1.color, cat1.kind);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: