js面向对象:封装

2017-03-27  本文已影响0人  day_day_up

封装

1.不合理:构造函数模式的问题

构造函数方法很好用,但是存在一个浪费内存的问题。
请看,我们现在为Cat对象添加一个不变的属性type(种类),再添加一个方法eat(吃)。那么,原型对象Cat就变成了下面这样:

function Cat(name,color){
    this.name = name;
    this.color = color;
    this.type = "猫科动物";
    this.eat = function(){alert("吃老鼠");};
  }
 var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat ("二毛","黑色");
  alert(cat1.type); // 猫科动物
  cat1.eat(); // 吃老鼠
  alert(cat1.eat == cat2.eat); //false

2.合理的方式:Prototype模式

 function Cat(name,color){
    this.name = name;
    this.color = color;
  }
 Cat.prototype.type = "猫科动物";
 Cat.prototype.eat = function(){alert("吃老鼠")};
var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat("二毛","黑色");
  alert(cat1.type); // 猫科动物
  cat1.eat(); // 吃老鼠
  alert(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()方法,用来判断某一个属性到底是本地属性,还是继承自prototype对象的属性。

alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false

3.3 .in运算符

in运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性。in运算符还可以用来遍历某个对象的所有属性。

alert("name" in cat1); // true
alert("type" in cat1); // true
  for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }

参考文档 ++Javascript 面向对象编程(一):封装

上一篇 下一篇

猜你喜欢

热点阅读