码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript对象

时间:2015-06-04 11:13:17      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

 

  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运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性。

JavaScript对象

标签:

原文地址:http://www.cnblogs.com/mingjing/p/4551014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!