javaScript 写一个简单的面向对象程序

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>简单的面向对象程序</title>
    <script>
        // 面向对象
        // 1、写构造函数
        function Aaa() {
            // 2、在构造函数里面添加属性
            this.name = '小明';
        }
        // 3、方法添加在原型上
        Aaa.prototype.showName = function() {
            alert( this.name );
        }
        // 使用面向对象 创建一个a1这样的对象
        var a1 = new Aaa()
        // 这个对象拥有它的属性和方法
        a1.showName();
    </script>
</head>
<body>
</body>
</html>

为什么要写面向对象程序?因为我们希望拥有像系统对象类似数组或者时间那样的形式

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>面向对象</title>
    <script>
        // 我们为什么要写面向对象程序 希望拥有像系统对象类似数组或者时间那样的形式
        //系统对象的用法,如数组
        var arr = new Array();
        arr.push();
        arr.sort();

        // 在JS源码内部:系统对象也是基于原型的程序
        // JS源码里面的数组对象
/*        function Array() {
            this.length = 0;
        }
        Array.prototype.push = function () {};
        Array.prototype.sort = function () {}
*/

        var arr = [1,2,3];
        arr.push(4,5,6);
        alert(arr); // 1,2,3,4,5,6

        // 假如我们push之前修改了Array对象的push()方法
        var arr = [1,2,3];
        // Array原本的push()方法被覆盖了
        Array.prototype.push = function () {
            // this : 1,2,3
            // arguments : 4,5,6
            for(var i=0; i<arguments.length;i++){
                this[this.length] = arguments[i]
            }
            return this.length;
        };
        arr.push(4,5,6);
        alert( arr );
        // 所以不要轻易修改系统对象下面的属性和方法,除非你特别了解,这样出现问题也知道怎么改
    </script>
</head>
<body>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值