面向对象编程(一)封装
构造函数模式
所谓"构造函数"
,其实就是一个普通函数,但是内部使用了this变量
。对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。
比如,猫的原型对象1
2
3
4function Cat(name, color) {
this.name = name;
this.color = color;
}
我们现在就可以生成实例对象了。1
2
3
4
5
6
7
8
9
10 var cat1 = new Cat ("大毛", "黄色");
var cat2 = new Cat ("二毛", "黑色");
alert(cat1.name); //大毛
alert(cat1.color); //黄色
```
这时的cat1和cat2会自动含有一个constructor属性,指向它们的构造函数。
```javascript
alert(cat1.constructor === Cat); //true
alert(cat2.constructor === Cat); //true
Javascript还提供了一个instanceof运算符,验证原型对象与实例对象之间的关系。1
2alert(cat1 instanceof Cat); //true
alert(cat2 instanceof Cat); //true
构造函数方法很好用,但是存在一个浪费内在的问题
Prototype 模式
Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。
这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。1
2
3
4
5
6function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype.type = "猫科动物";
Cat.prototype.eat = function(){alert("吃老鼠")};
然后,生成实例。1
2
3
4var cat1 = new Cat ("大毛", "黄色");
var cat2 = new Cat ("二毛", "黑色");
alert(cat1.type); //猫科动物
cat1.eat(); //吃老鼠
这时所有实例的type属性和eat()方法,其实都是同一个内存地址,指向prototype对象,因此就提高了运行效率。
Prototype 模式的验证方法
isPrototypeOf()
这个方法用来判断,某个proptotype对象和某个实例之间的关系。1
2alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
hasOwnProperty()
每个实例对象都有一个hasOwnProperty()方法,用来判断某一个属性到底是本地属性,还是继承自prototype对象的属性。1
2alert(cat1.hasOwnProperty("name")); //true
alert(cat1.hasOwnProperty("type")); //false
in 运算符
1 | for(var prop in cat1) {alert("cat1["+prop+"]="+cat1[prop]);} |