美文网首页
如何"封装"数据和方法,以及如何从原型对象生成实例

如何"封装"数据和方法,以及如何从原型对象生成实例

作者: 露露璐璐 | 来源:发表于2018-05-11 16:18 被阅读0次

所谓"构造函数",其实就是一个普通函数,但是内部使用了[this变量。对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上,
比如,猫的原型对象现在可以这样写,

  function Cat(name,color){

    this.name=name;

    this.color=color;

  }

我们现在就可以生成实例对象了

  var cat1 = new Cat("大毛","黄色");

  var cat2 = new Cat("二毛","黑色");

  alert(cat1.name); // 大毛

  alert(cat1.color); // 黄色

这时cat1和cat2会自动含有一个constructor属性,指向它们的构造函数。

 alert(cat1.constructor == Cat); //true

  alert(cat2.constructor == Cat); //true

Javascript还提供了一个instanceof运算符,验证原型对象与实例对象之间的关系。

 alert(cat1 instanceof Cat); //true

  alert(cat2 instanceof Cat); //true

Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。
这意味着,我们可以把那些不变的属性和方法,直接定义在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(); // 吃老鼠

这时所有实例的type属性和eat()方法,其实都是同一个内存地址,指向prototype对象,因此就提高了运行效率。

 alert(cat1.eat == cat2.eat); //true

isPrototypeOf():这个方法用来判断,某个proptotype对象和某个实例之间的关系。

  alert(Cat.prototype.isPrototypeOf(cat1)); //true
  alert(Cat.prototype.isPrototypeOf(cat2)); //true

hasOwnProperty():每个实例对象都有一个hasOwnProperty()方法,用来判断某一个属性到底是本地属性,还是继承自prototype对象的属性。

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

in运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性。

 alert("name" in cat1); // true
 alert("type" in cat1); // true

in运算符还可以用来遍历某个对象的所有属性。

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

相关文章

网友评论

      本文标题:如何"封装"数据和方法,以及如何从原型对象生成实例

      本文链接:https://www.haomeiwen.com/subject/jcnfdftx.html