• js_03 面向对象


    2.对象和关联数组

      js的对象本质上是一个关联数组, 说白了就是咱python中的字典

      对象的每个实力属性就是一个键值对

      实例方法也是一个键值对, 只不过value值是一个函数

        var Person = function(name, age)
        {
            this.name = name;
            this.age = age;
            this.info = function()
            {
                alert('this is info method')
            }
        }
    
        var p = new Person('zhangjian', 18);
        for (propname in p)
        {
            document.writeln('p 对象的' + propname + '属性值为' + p[propname] + '<br>')
        }

    运行结果

    p 对象的name属性值为zhangjian
    p 对象的age属性值为18
    p 对象的info属性值为function() { alert('this is info method') }

    3. 继承prototype

      js虽然有类和对象的概念, 但是没有明显的继承关系, 所有的类都是object对象的子类

      可以动态的为对象添加属性和方法

      

        //定义一个空对象
        var p = {};
        // 动态的添加属性和方法
        p.name = 'zhangjian';
        p.info = function()
        {
            alert('this is info method')
        };
    
        p.info()

    我们可以在定义类(其实就是个函数)的时候在内部为这个类定义实例方法, 但是这样有两个缺点,

      1.每次实例化一个对象都生成了这样一个函数,容易造成内存泄露

      2. 形成了一个闭包,增大了局部变量的作用范围

    prototype

      为了避免上述情况,通常不建议直接在函数定义中直接为该函数定义方法,而是建议使用prototype属性

      js的所有类都有一个prototype属性,如果为js的prototype属性添加属性,方法,则可视为对所有类的扩展.

    <script>
        var Person = function(name, weight)
        {
            this.name = name;
            this.weight = weight;
            this.info = function () {
                document.writeln(this.name + '<br>');
                document.writeln(this.weight + '<br>');
            }
        }
    
        var zj = new Person('zhangjian', 18);
        zj.info();
      // 通过prototype为Person类添加方法,这个方法会被所有(包括已经创建的对象继承)
        Person.prototype.walk = function () {
            for(;;){
                if (this.weight >= 5)
                {
                    this.weight -= 5;
                    this.info();
                }
                else
                {
                    return
                }
    
            }
    
        };
        zj.walk();
    </script>

    使用prototype对js内建类进行拓展

      例: 为jsArray内建类添加indexof方法,返回输入元素的索引,没有则返回-1

    <script>
        Array.prototype.indexOf = function (obj) {
            ret = -1;
            for (i=0; i<this.length; i++)
            {
                if (this[i] == obj)
                {
                    ret = i;
                    break
                }
            }
            return ret
        }
    
        a = Array(1,2,3,4,5,6);
        alert(a.indexOf(6));
        alert(a.indexOf(7))
    
    </script>

      

  • 相关阅读:
    python中zip函数
    python中创建列表、元组、字符串、字典
    python中enumerate函数
    python中字符串的拼接
    python中格式化浮点数及科学计数法
    python中tuple函数
    python中可迭代对象的排序
    python中变量类型转换
    python中可迭代对象反转
    python中list函数
  • 原文地址:https://www.cnblogs.com/zhangjian0092/p/11768102.html
Copyright © 2020-2023  润新知