Javascript 面向对象编程(一):封装
确定实例之间没有联系。不能反映出它们是同一个原型对象的实例。没有指向他们的构造函数。
function Cat(name,color) {
return {
name:name,
color:color
}
}
const cat1 = new Cat('大猫', 'red'); const cat2 = new Cat('小猫', 'black');
cat1.constructor == Cat
false
改进1:通过this绑定,指向他们的构造函数
function Cat(name,color) {
this.name = name;
this.color = color;
}
const cat1 = new Cat('大猫', 'red'); const cat2 = new Cat('小猫', 'black');
cat1.constructor == Cat
true
还可以为这个这些增加实例方法
function Cat(name,color){
this.name = name;
this.color = color;
this.type = "猫科动物";
this.eat = function(){alert("吃老鼠");};
}
cat1.eat();
cat2.eat();
cat1.eat == cat2.eat // false
cat1.eat.prototype == cat2.eat.prototype // false
里面的构造函数不一样
缺点:每次实例调用都会属性方法都会浪费内存。prototype应运而生
function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "猫科动物";
Cat.prototype.eat = function(){alert("吃老鼠")};
const cat1 = new Cat('大猫', 'red'); const cat2 = new Cat('小猫', 'black');
此时type,eat都指向同一个内存地址,也就是Cat的prototype对象。
cat1.eat == cat2.eat // true
3.Prototype模式的验证方法
3.1.isPrototypeOf()
这个方法用来判断,某个proptotype对象和某个实例之间的关系。
alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
3.2.hasOwnProperty(),
每个实例对象都有一个hasOwnProperty()方法,用来判断某一个属性到底是本地属性(是否是construct属性),还是继承自prototype对象的属性。
alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false
3.3.in运算符
in运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性。
alert("name" in cat1); // true
alert("type" in cat1); // true