JavaScript面向对象及原型继承(实例)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript的原型继承</title>
<script>
/*Description: 这段js主要是讲述如何创建JavaScript对,象,以及JavaScript的原型继承*/
//创建一个对象 的第一种方式
var Hello = function(){
var msg = "Hello World";
this.println = function(printMsg){
printMsg = printMsg || msg;
document.writeln(printMsg + "<br>");
}
}

var hello = new Hello();
hello.println("Hello yelb");
hello.println();
document.writeln("<br>******************************************************<br>");
//创建狗的类
var Dog = function(){
}; // var Dog = new Object(); 这几种是创建类的效果是一样的,var Dog = {}这种方式创建的对象是没用prototype,没有构造器的。
Dog.prototype = {
eat: function(){
document.writeln("the dog eat dog-food<br>");
},
run: function(){
document.writeln("the dog run for joy<br>");
},
sleep: function(){
document.writeln("the dog so tire,so it sleep<br>");
}
}

var dog = new Dog();
dog.eat();
dog.run();
dog.sleep();
document.writeln("<br>******************************************************<br>");
//js继承的两种方式--第一种
var Collie = function(){
};//古代长须牧羊犬
Collie.prototype = new Dog();
Collie.prototype.action = function(){
document.writeln("Collie's actions is eat,run,sleep<br>");
}
var collie = new Collie();
collie.eat();
collie.run();
collie.sleep();
collie.action();
document.writeln("<br>******************************************************<br>");
//js继承的两种方式--第二种
var Bulldog = function(){ //Bulldog:老虎犬
var dog = new Dog();
for (var key in dog) {
this[key] = dog[key];
}
this.action = function(){
document.writeln("I'll show Bulldog special actions<br>");
this.eat();
this.run();
this.sleep();
}
}
var bulldog = new Bulldog();
bulldog.action();
document.writeln("<br>******************************************************<br>");

/**

var Test = {};

var test = new Test();//这种做法是失败的

*/

</script>
</head>
<body>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值