面向对象的JS代码

在下面的例子中可以找到强类型语言中所描述的类,属性,方法,对象。

<script language="javascript" type="text/javascript">

        //定义了类型Leature[构造函数]

        function Lecture(name, tea) {

            this.name = name; //将参数保存为对象的局部属性

            this.teacher = tea;

        }

 

        //定义原型方法[类上的方法]

        Lecture.prototype.display = function() {

            return this.teacher + " is teaching " + this.name;

        };

 

        //定义类型Schedule[构造函数],接收参数为Lecture的数组

        function Schedule(leatures) {

            this.leatures = leatures;

        }

        //类Schedule的方法

        Schedule.prototype.display = function() {

            var str = "";

            for (var i = 0; i < this.leatures.length; i++) {

                str += this.leatures[i].display() + " ";

            }

            return str;

        };

        //创建类型Schedule的一个对象mySchedule,并实例化。

        var mySchedule = new Schedule([

            new Lecture("a", "A"),

            new Lecture("b", "B"),

            new Lecture("c", "C")

            ]);

        alert(mySchedule.display());

</script>

this出现在构造函数中,更多的是表示一种特有的属性;

prototype主要用于拓展函数的属性,方法。

在函数类实例化的时候,this的属性需要复制相应的副本,prototype不用。

 

原文地址:https://www.cnblogs.com/hometown/p/3204224.html