js oop学习笔记

翻书的时候翻到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>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值