javascript原型链初识

来源:互联网 发布:淘宝双12店铺活动方图 编辑:程序博客网 时间:2024/06/15 22:53
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>初识js原型链</title></head><body>    <script>        function SuperType(){            this.property="whyme";        }        SuperType.prototype.getSuperValue=function(){            return this.property;        }        function SubType(){            this.subproperty=false;        }        //继承了SuperType        SubType.prototype=new SuperType();        SubType.prototype.getSubValue=function(){            return this.subproperty;        }        var instance=new SubType();//instance.constructor指向的是SuperType                                    //这是因为原来的SubType.prototype中的constructor被重写了的缘故。        alert(instance.getSuperValue()); // "whyme"        //当以读取模式访问一个实例属性时,首先会在实例中搜索该属性。如果没有找到该属性,则会继续搜索实例的原型。        // 在通过原型链实现继承的情况下,搜索过程就得以沿着原型链继续向上        //上面的例子中,调用instance.getSuperValue()会经历三个搜索步骤        //1、搜索实例  2、搜索SubType.prototype;  3、搜索SuperType.prototype,        // 最后一步才会找到该方法。        //在找不到属性或方法的情况下,搜索过程总是要一环一环地前行到原型链末端才会停下来。        //所有引用类型默认都继承了Object,而这个继承也是通过原型链实现的。因此,所有函数的默认原型都是        //Object的实例。    </script></body></html>

1、原型对象、实例和构造函数的关系

2、上述例子完整的原型链视图

3、确定原型和实例的关系

    第一种方式:是使用instanceof操作符,只要用这个操作符来测试实例与原型链中出现过的构造函数,结果就会返回true。

alert(instance instanceof Object); //true

alert(instance instanceof SuperType); //true

alert(instance instanceof SubType); //true

由于原型链的关系,我们可以说instance是Object、SuperType或SubType中任何一个类型的实例。因此,测试这三个构造函数的结果都返回true.

  第二种方式是使用isPrototypeOf()方法。同样,只要是原型链中出现过的原型,都可以说是该原型链所派生的实例的原型。因此isPrototypeof()方法也会返回true。

alert(Object.prototype.isPrototypeOf(instance));

alert(SuperType.prototype.isPrototypeOf(instance));

alert(SubType.prototype.isPrototypeOf(instance));

0 0
原创粉丝点击