日期:2014-05-16  浏览次数:20374 次

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();