• JavaScript的prototype是什么


    所有对象都有prototype,prototype自身也是对象,它有prototype,这样就形成了prototype链。当遇到有链中为null时,链就终止了,object的prototype就是null.
    上面内容http://www.javaeye.com/article/53537有介绍,
    然而有太多问题需要想明白了。
    prototype它是一种数据结构,还是别的什么。
    function class1(name)
    {
        this.class1Name=name;
    }
    function class2(name)
    {
        this.class2Name=name;
    }
    function class3(name)
    {
       this.class3Name=name;
    }
    class3.prototype=new class1('class1');//把一个对象class1替换(用这个词感觉不对)prototype
    class3.prototype.abc='abc';然而此时还能通过prototype添加属性。 目前按照我的理解,prototype不是一个简单的对象。
    class3.prototype=new class2('class2');//这一步后abc属性就不存在了。

    接下来说一下对象对属性的访问。
    这个是上面链接中的原话:
    读操作会读取在obj自己和prototype 链上发现的第一个同名属性值
    写操作会为obj对象本身创建一个同名属性(如果这个属性名不存在
    这里要注意同名属性,如下
    function class1()
    {
       this.className='class1';
    }
    function class2()
    {}
    class2.prototype=new class1();
    alert(new class2().className)//这里结果为class1;说明访问到了class1中的className属性。
    class2.prototype.class1=new class1();
    alert(new class2().className)//这里结果为undefined,说明没有访问到className属性。
    所以在属性访问上是根据属性名的,就算这个属性held的是一个对象。而不会去访问到下面的prototype中去。

    下面说一下this这个关键字。
    function class1(name)
    {
        this.user=name;
    }
    class1.prototype=
    {
        firstName:function()
            {
                return this.user;
            }
    }
    function class2(name)
    {
        this.name=name;
    }
    class2.prototype=new class1('class1');
    alert(new class2('class2').firstName());//这里结果应该能想到是class1.
    但是如果这样写,把function class1的的代码改成如下:
    function class1(name)
    {
       this.name=name;
    }
    class1.prototype=
    {
       firstName:function()
          {
             return this.name;
          }
    }

    alert(new class2('class2').firstName());//此时输出的结果就是class2;
    开始class2访问firstName方法,它便在自己成员中查找,没有找到,就在prototype中查找。这时它在class1中找到了fristName
    而class1中firstName方法返回this.name,这个this指的还是class2.所以它又会在class2的成员中查找。所以这里的结果是class2;

    对JavaScript一直都不太清楚,现在更迷惑了。希望明白人说一下。
    另外Function 和Object是个奇怪的东西。

  • 相关阅读:
    cmake 学习记录
    OCRTesseract
    IEquatable<T>、IEnumerable<T>
    基于jackson 注解 入参 枚举 反序列化 实操
    基于jackson 将一个String 类型的Json字符串对外输出成 json 格式。
    mysql 中sql 语句查询今天、昨天、7天、近30天、本月、上一月 数据
    mysql 计算两个日期的天数
    iis上json解析失败404
    mybatis foreach split
    mybatis中大于等于小于等于的写法
  • 原文地址:https://www.cnblogs.com/bmrxntfj/p/822616.html
Copyright © 2020-2023  润新知