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

js oop学习笔记

2013-03-24 09:35 274 查看
翻书的时候翻到js oop,正好之前没有系统学习过,再复习一下,代码仅供参考学习

<script type="text/javascript">

Animal=function(tail){

 this.tail=tail;

}

Animal.prototype={

  happy:function(){

   alert(this.tail+" 动物很高兴");//这里注意 由于构造器传递的参数在this作用域 如果不写this 无法获取到tail属性

  },

  eat:function(){

   alert("动物吃东西");

  },

  run:function(){

   alert("动物跑得快");

  }

};

Animal.prototype.constructor=Animal;//设置构造器

var animal=new Animal("有尾巴");

alert(animal.tail);

animal.run();

animal.happy();

</script

 

下面演示了delete关键字和重置构造器的用法

<script>

Animal=function(tail){

 this.tail=tail || "动物的尾巴";

}

Animal.prototype={

  happy:function(){

   alert("动物很高兴 "+this.tail);

  },

  run:function(){

   alert("动物在跑");

  }

};

Animal.prototype.constructor=Animal;

Person=function(name){

 this.name=name;

}

Person.prototype=new Animal();//在这里 person的constructor被覆盖掉了 alert p.constructor得到的是animal的构造器

Person.prototype.constructor=Person; //上面覆盖了constructor 这里再覆盖回来 但是只覆盖构造器

var p=new Person("xiao li");

alert(p.name+p.tail);

delete Person.prototype.tail; //这里吧tail属性去掉了 所以下面用到tail的话 都是undefined

alert("剪掉了 "+p.tail);

p.run();

p.happy();

alert(p.constructor);//这样弹出的就是person的构造器了

</script>

 

对象冒充 也就是call方法的用法:

<script>

Animal=function(tail){

 this.tail=tail || "动物";

}

Animal.prototype={

  happy:function(){

   alert("happy");

  }

};

Animal.prototype.constructor=Animal;

Person=function(name){

 this.name=name;

 Animal.call(this); //这里继承了Animal的所有this下的属性 方法不会被继承

 alert(this.tail);

 //delete this.tail; //可以删除掉其中不需要的属性

}

var p=new Person("aaaa");

alert(p.name+" "+p.tail);

</script>

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: