对prototype,instanceof和constrctor的理解

<!DOCTYPE html>
<html>
<head>
<script>
function Cat(name,color){
  this.name=name;
  this.color=color;
  this.eat=function(){console.log('eat fish');} 
}

var cat1=new Cat('ketty','black');
console.log(cat1.name);
console.log(cat1 instanceof Cat);//true 只要是new运算符实例化的对象 都是它的构造函数的实例 即 cat1=new Cat('nn','cc') cat1 Cat总是实例和类的关系
console.log(cat1.constructor); //Cat  读取prototype对象中的constructor属性的值,
//每个函数对象(不管普通函数还是构造函数)都有
prototype属性(属性值为对象),prototype对象中默认存在constructor属性,属性值指向构造函数自身 测试如下:
function Test(){}
console.log(Test.prototype.constructor); //Test
//若直接给函数的prototype属性赋值 将丢失constructor这个默认属性值 如:
//Cat.prototype={a:22}; //Object对象的字面量 Object对象prototype默认有属性constructor:Object;
//console.log(cat1.constructor); //Object
console.log(cat1.prototype); //undefined. prototype是function对象的属性 

console.log(cat1.constructor.prototype); //Cat{}
</script> </head> <body> </body> </html>

 

posted @ 2013-04-16 14:44  stephenykk  阅读(396)  评论(0编辑  收藏  举报