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

JavaScript对象

2015-06-04 10:08 169 查看

  function Cat(name,color){

    this.name=name;

    this.color=color;

  }

猫类




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

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

  alert(cat1.name); // 大毛

  alert(cat1.color); // 黄色

实例


constructor属性 指向类

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

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

  alert(cat2.constructor); //function Cat(name, color) { this.name = name; this.color = color; this.type = "猫类"; this.eat = function () { alert("吃饭");}}

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

  alert(cat1 instanceof Cat); //true

  alert(cat2 instanceof Cat); //true

Prototype属性 Javascript规定,每一个构造函数都有一个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(cat2.constructor); //function Cat(name, color) { this.name = name; this.color = color; this.type = "猫类"; this.eat = function () { alert("吃饭");}}


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

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

aaain运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: